Pattern: Assigning array to a string
Issue: -
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
).
If you want to assign N elements as N elements, use an array, e.g. someArray=( "$@" )
.
If you want to assign N elements as 1 element by concatenating them, use *
instead of @
, e.g. someVar=${someArray[*]}
(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.
Example of incorrect code:
var=$@
for i in $var; do ..; done
or
set -- Hello World
msg=$@
echo "You said $msg"
Example of correct code:
var=( "$@" )
for i in "${var[@]}"; do ..; done
or
set -- Hello World
msg=$*
echo "You said $msg"