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?

1 Answer 1

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.

3
  • XD thanks for the reply, I was like going to answer this myself, some further explanation tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
    – Jeffrey04
    May 25, 2009 at 9: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? Feb 7, 2012 at 9: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". Feb 13, 2012 at 11:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.