6

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.

1

2 Answers 2

15

Quote $@:

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

Output:

x y
z
3
  • 7
    For some versions (at least) of bash, it's enough to say for a. It will assume that you mean in "$@". Mar 23, 2015 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. Mar 23, 2015 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. Mar 24, 2015 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.
1
  • See Scott's comment.
    – Cyrus
    Mar 24, 2015 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.