Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash array variables: [@] or [*]?

Tags:

bash

bash-3.2$ echo astr | sed 'hah' | sed 's/s/z/'
sed: 1: "hah": extra characters at the end of h command
bash-3.2$ echo ${PIPESTATUS[*]}
0 1 0
bash-3.2$ echo astr | sed 'hah' | sed 's/s/z/'
sed: 1: "hah": extra characters at the end of h command
bash-3.2$ PIPERET=("${PIPESTATUS[*]}")
bash-3.2$ echo ${PIPERET[*]}
0 1 0
bash-3.2$

This indicates that [*] works fine. But this tut mentions to use [@] instead.

Are both equally valid?

like image 590
Steven Lu Avatar asked May 18 '13 19:05

Steven Lu


2 Answers

The difference matters mainly when the array elements contain spaces etc. and especially multiple spaces, and is only manifest when the expressions are enclosed in double quotes:

$ x=( '   a  b  c   ' 'd  e  f' )
$ printf "[%s]\n" "${x[*]}"
[   a  b  c    d  e  f]
$ printf "[%s]\n" "${x[@]}"
[   a  b  c   ]
[d  e  f]
$ printf "[%s]\n" ${x[@]}
[a]
[b]
[c]
[d]
[e]
[f]
$ printf "[%s]\n" ${x[*]}
[a]
[b]
[c]
[d]
[e]
[f]
$

Outside double quotes, there's no difference. Inside double quotes, * means 'a single string' and @ means 'array elements individually'.

It is closely analogous to the way $* and $@ (and "$*" and "$@") work.

See the bash manual on:

  • arrays
  • special parameters
like image 178
Jonathan Leffler Avatar answered Sep 28 '22 15:09

Jonathan Leffler


To quote man bash

If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a sep- arate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word.

like image 23
parkydr Avatar answered Sep 28 '22 15:09

parkydr