Bash – Why doesn’t $@ work when passing strings

bash

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.

Best Answer

Quote $@:

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

Output:

x y
z
Related Question