tags:

views:

35

answers:

3

Let's say I have a really simple shell script 'foo':

  #!/bin/sh
  echo $@

If I invoke it like so:

  foo 1 2 3

It happily prints:

  1 2 3

However, let's say one of my arguments is double-quote enclosed and contains whitespace:

  foo 1 "this arg has whitespace" 3

foo happily prints:

  1 this arg has whitespace 3

The double-quotes have been stripped! I know shell thinks its doing me a favor, but... I would like to get at the original version of the arguments, unmolested by shell's interpretation. Is there any way to do so?

--Steve

A: 

You need to quote the quotes:

foo 1 "\"this arg has whitespace\"" 3

or (more simply)

foo 1 '"this arg has whitespace"' 3

You need to quote the double quotes to make sure that the shell doesn't remove them when parsing word arguments.

Burton Samograd
+2  A: 

First, you probably want quoted version of $@, i.e. "$@". To feel the difference, try putting more than one space inside the string.

Second, quotes are element of shell's syntax -- it doesn't do you a favor. To preserve them, you need to escape them. Examples:

foo 1 "\"this arg has whitespace\"" 3

foo 1 '"this arg has whitespace"' 3
Roman Cheplyaka
A: 

Double quote $@:

#!/bin/sh
for ARG in "$@"
do
    echo $ARG
done

Then:

foo 1 "this arg has whitespace" 3

will give you:

1
this arg has whitespace
3
Alex Howansky