Skip to content
koalaman edited this page Apr 5, 2014 · 11 revisions

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

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).

Contraindications

None.

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally