From 058d9fd73c2647071d335b537bc594151ab46420 Mon Sep 17 00:00:00 2001 From: Maddison Hellstrom Date: Sun, 9 Feb 2020 17:00:15 -0800 Subject: [PATCH] describe workaround to local variable confusion --- SC2178.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/SC2178.md b/SC2178.md index 4d95595..c6749ad 100644 --- a/SC2178.md +++ b/SC2178.md @@ -39,3 +39,34 @@ Another possible cause is accidentally missing the `$` on a previous assignment: ### Exceptions: 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" +} +``` \ No newline at end of file