Friday 18 August 2017

Bash [@] vs [*]

Cited from the Book "Pro Bash Programming"

The subscripts @ and * are analogous to their use with the positional parameters: * expands to a single parameter if quoted; if unquoted, word splitting and file name expansion is performed on the result. Using @ as the subscript and quoting the expansion, each element expands to a separate argument, and no further expansion is performed on them.

$ printf "%s\n" "${BASH_VERSINFO[*]}"
4 0 10 1 release i686-pc-linux-gnuoldld
$ printf "%s\n" "${BASH_VERSINFO[@]}"
4
0
10
1
release
i686-pc-linux-gnuoldld

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When Bash (or any similar shell) parses a command line, it splits it into a series of "words" (which I will call "shell-words" to avoid confusion later). Generally, words are separated by spaces (or other whitespace), but spaces can be included in a word by escaping or quoting them. The difference between [@] and [*]-expanded arrays in double-quotes is that "${myarray[@]}" leads to each element of the array being treated as a separate shell-word, while "${myarray[*]}" results in a single shell-word with all of the elements of the array separated by spaces (or whatever the first character of IFS is).

No comments:

Post a Comment