Friday 7 March 2014

Bash arrays - what is the difference between array[*] and array[@]?

I've just been updating some Bash scripts and noticed that there are two ways to refer to array elements: one using the "*" the other using "@". So what is the difference? According to the manual
The "@" variable allows word splitting within quotes (extracts variables separated by whitespace). This corresponds to the behaviour of "$@" and "$*" in positional parameters.
So you get two different outcomes as demonstrated below:
$ ARRAY=(0 1 2 3 4 5 6 7 8 9)
 
# first using "@" inside quotes,
# you get the same output with no quotes ...
$ for i in "${ARRAY[@]}"; do echo "$i"; done
0
1
2
3
4
5
6
7
8
9
 
# same as above but using "*" ...
$ for i in "${ARRAY[*]}"; do echo "$i"; done
0 1 2 3 4 5 6 7 8 9
 
# but without quotes ...
$ for i in ${ARRAY[*]}; do echo "$i"; done
0
1
2
3
4
5
6
7
8
9
Source: http://www.tldp.org/LDP/abs/html/arrays.html