Bash – Difference Between [@] and [*] When Referencing Bash Array Values

arraybash

This Bash guide says:

If the index number is @ or *, all members of an array are referenced.

When I do this:

LIST=(1 2 3)
for i in "${LIST[@]}"; do
  echo "example.$i"
done

it gives the desired result:

example.1
example.2
example.3

But when I use ${LIST[*]}, I get

example.1 2 3

instead.

Why?

Edit: when using printf, @ and * actually do give the same results.

Best Answer

The difference is subtle; "${LIST[*]}" (like "$*") creates one argument, while "${LIST[@]}" (like "$@") will expand each item into separate arguments, so:

LIST=(1 2 3)
for i in "${LIST[@]}"; do
    echo "example.$i"
done

will deal with the list (print it) as multiple variables.

But:

LIST=(1 2 3)
for i in "${LIST[*]}"; do
    echo "example.$i"
done

will deal with the list as one variable.

Related Question