views:

47

answers:

1

In a shell script I want a variable p to be equal to "$@", so that the following two lines of code produce the same result:

for x in "$p"; do echo $x; done
for x in "$@"; do echo $x; done

If I do p=$@ or p="$@" this doesn't work. When the command line arguments have spaces in their names, I can't find a simple workaround to this problem (the combination p="$@" and for x in $p (quotes removed around $p) works when there are no spaces).

+4  A: 

"$@" is special in that it even though it is a single quoted expression it expands to zero or more “words”. You can not accomplish the same thing with a normal parameter, but (using a slightly different syntax) it can be done with an array variable/parameter (e.g. in bash, ksh, zsh):

array_var=("$@")
for x in "${array_var[@]}"; do printf '<<%s>>\n' "$x"; done
Chris Johnsen