5

For example, using this script:

#!/bin/bash
for a in $@
do
   echo $a
done

And running:./script "x y" z returns:

x
y
z

and not:

x y
z


Why is that?
And how would I pass string arguments with spaces to bash?

I use Bash 4.3.33.

16

Quote $@:

#!/bin/bash
for a in "$@"
do
  echo "$a"
done

Output:

x y
z
  • 7
    For some versions (at least) of bash, it's enough to say for a. It will assume that you mean in "$@". – Scott Mar 23 '15 at 19:25
  • On a side note, how does one do this with introducing a variable? For example T=$@ for a in $T do echo "$a" done does not work. – orange orange Mar 23 '15 at 23:01
  • 2
    @orangeorange You can't safely store multiple arguments in a plain variable. But you can store them in an array with t=("$@"), and then reference it as "${t[@]}" to recover the original argument list intact. Note that all of the double-quotes I used are necessary. – Gordon Davisson Mar 24 '15 at 1:16
3

Note that in when dealing with $@ you can simplify it to

for a
do
   echo "$a"
done
If `in WORDS ...;' is not present, then `in "$@"' is assumed.
  • See Scott's comment. – Cyrus Mar 24 '15 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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