menders65
menders65

Reputation: 43

What is the difference between echo "${array[@]}" echo "${array[*]}" in bash

I get the same results with both echo "${array[@]}" and echo "${array[*]}".
If I do:
mkdir fakemusic; touch fakemusic/{Beatles,Stone,Ramones,Doors}{001..199}; cd fakemusic.
Then _msc=(*)
These two commands give me identical output:

echo "${_msc[@]}"  
echo "${_msc[*]}"  

So what is the difference between them.

Upvotes: 2

Views: 1385

Answers (1)

Joni
Joni

Reputation: 111379

The shell expands "${_msc[@]}" as separate strings, while it expands "${_msc[*]}" as a single string, with the items separated by space by default. You can't see the difference with echo because it also uses a space as a separator. Here's an example with printf:

$ printf "%s;%s;%s\n" "${_msc[@]}"
a;b;c
$ printf "%s;%s;%s\n" "${_msc[*]}"
a b c;;

The shell variable IFS controls which character is used as the separator. If you change it you can see the difference with echo too:

$ IFS='|'
$ echo "${_msc[*]}"    # shell expands to a single string
a|b|c
$ echo "${_msc[@]}"    # shell expands to a separate string
a b c

Upvotes: 6

Related Questions