< Previous | Contents | Next >
Outputting The Entire Contents Of An Array
The subscripts * and @ can be used to access every element in an array. As with posi- tional parameters, the @ notation is the more useful of the two. Here is a demonstration:
[me@linuxbox ~]$ animals=("a dog" "a cat" "a fish") [me@linuxbox ~]$ for i in ${animals[*]}; do echo $i; done a
dog a cat a fish
[me@linuxbox ~]$ for i in ${animals[@]}; do echo $i; done
a dog a cat a fish
[me@linuxbox ~]$ for i in "${animals[*]}"; do echo $i; done
a dog a cat a fish
[me@linuxbox ~]$ for i in "${animals[@]}"; do echo $i; done
a dog a cat a fish
[me@linuxbox ~]$ animals=("a dog" "a cat" "a fish") [me@linuxbox ~]$ for i in ${animals[*]}; do echo $i; done a
dog a cat a fish
[me@linuxbox ~]$ for i in ${animals[@]}; do echo $i; done
a dog a cat a fish
[me@linuxbox ~]$ for i in "${animals[*]}"; do echo $i; done
a dog a cat a fish
[me@linuxbox ~]$ for i in "${animals[@]}"; do echo $i; done
a dog a cat a fish
We create the array animals and assign it three two-word strings. We then execute four loops to see the affect of word-splitting on the array contents. The behavior of notations $
{animals[*]} and ${animals[@]} is identical until they are quoted. The * nota- tion results in a single word containing the array’s contents, while the @ notation results in three two-word strings, which matches the array's “real” contents.