Skip to content
ebersphi edited this page Mar 4, 2020 · 15 revisions

Assigning an array to a string! Assign as array, or use * instead of @ to concatenate.

Danger!

Changing this parameter can be dangerous. Its behavior is influenced by the value of IFS. In certain situations (like feeding strings into commands) this can result in unexpected results from a seemingly aesthetic-only change. [More info]

Problematic code:

var=$@
for i in $var; do ..; done

or

set -- Hello World
msg=$@
echo "You said $msg"

Correct code:

var=( "$@" )
for i in "${var[@]}"; do ..; done

or

set -- Hello World
msg=$*
echo "You said $msg"

Rationale:

Arrays and $@ can contain multiple elements. Simple variables contain only one. When assigning multiple elements to one element, the default behavior depends on the shell (bash concatenates with spaces, zsh concatenates with first char of IFS).

Since doing this usually indicates a bug, ShellCheck warns and asks you to be explicit about what you want.

If you want to assign N elements as N elements, use an array, e.g. myArray=( "$@" ).

If you want to assign N elements as 1 element by concatenating them, use * instead of @, e.g. myVar=${myArray[*]} (this separates elements with the first character of IFS, usually space).

The same is true for ${@: -1}, which results in 0 or 1 elements: var=${*: -1} assigns the last element or an empty string.

Exceptions

None.

Adding an element to an array may trigger this warning when you forget the parenthesis.

filelist="${filelist[@]}" "$filename"

What was meant is:

filelist=("${filelist[@]}" "$filename")

Note: this syntax is compatible with older shells, in later shells (bash 3.1+ and zsh 4.2+) you can do: filelist+=("$filename")

Clone this wiki locally