From 969523cfd8aec3b6d33b3f93190792734a7e5905 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 5 Apr 2014 14:43:28 -0700 Subject: [PATCH] Created SC2124 (markdown) --- SC2124.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 SC2124.md diff --git a/SC2124.md b/SC2124.md new file mode 100644 index 0000000..91c490a --- /dev/null +++ b/SC2124.md @@ -0,0 +1,37 @@ +## 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. \ No newline at end of file