From 8fcfa824cfac139bf81110c7deda2e4e52c76939 Mon Sep 17 00:00:00 2001 From: Maddison Hellstrom Date: Sun, 9 Feb 2020 17:02:21 -0800 Subject: [PATCH] describe workaround to local variable confusion --- SC2128.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/SC2128.md b/SC2128.md index 8d71c24..d1d5773 100644 --- a/SC2128.md +++ b/SC2128.md @@ -30,4 +30,35 @@ To get all elements as a single parameter, concatenated by the first character i ### Exceptions -None. +ShellCheck can get confused by variable scope if the same variable name was used as an array previously, but is a string in the current context. You can [[ignore]] it in this case. + +In the case of local variables, a workaround is to declare the local variable separately from assigning to it: + +**Problematic Code:** +```sh +foo () { + local -a baz + baz+=("foo" "bar") + echo "${baz[@]}" +} + +bar () { + local baz="qux" + echo "$baz" +} +``` + +**Correct Code:** +```sh +foo () { + local -a baz + baz+=("foo" "bar") + echo "${baz[@]}" +} + +bar () { + local baz + baz="qux" + echo "$baz" +} +```