36

I need my script to be able to accept arguments with space characters. If, for example, I have a script as follows:

for SOME_VAR in $@
do
    echo "$SOME_VAR"
    cd "$SOME_VAR"
done;

If I pass arguments to the script (assuming it is called foo.sh)

sh foo.sh "Hello world"

I am expecting the script to print Hello world and change the directory to Hello world. But I get this error message instead:

hello
cd: 5: can't cd to hello
world
cd: 5: can't cd to world

How exactly do I pass an argument with a space character to a command in a shell script?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Jeffrey04
  • 6,138
  • 12
  • 45
  • 68

1 Answers1

53

You must wrap the $@ in quotes, too: "$@"

This tells the shell to ignore spaces in the arguments; it doesn't turn all arguments into a very long string.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • XD thanks for the reply, I was like going to answer this myself, some further explanation http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST – Jeffrey04 May 25 '09 at 09:05
  • But if $@ is a list putting " around it would basically merge it into one long string. It wouldn't iterate over it right? And in that case there is no real use in having a for loop, a normal `echo "$@"; cd "$@"` would do. Is there a solution where I can have `for i in `-constructs delimit on line break but not space? – Andreas Wederbrand Feb 07 '12 at 09:16
  • 4
    @AndreasWederbrand: No. "$@" is a special token which means "wrap each individual argument in quotes". So `a "b c"` becomes (or rather stays) `"a" "b c"` instead of `"a b c"` or `"a" "b" "c"`. – Aaron Digulla Feb 13 '12 at 11:09