From 72e514157f53764f7bcd562861b660364cec6240 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Thu, 7 Oct 2021 19:01:22 -0700 Subject: [PATCH] Created SC2313 (markdown) --- SC2313.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SC2313.md diff --git a/SC2313.md b/SC2313.md new file mode 100644 index 0000000..d487025 --- /dev/null +++ b/SC2313.md @@ -0,0 +1,29 @@ +## Quote array indices to avoid them expanding as globs. + +### Problematic code: + +```sh +read -r foo[index] +``` + +### Correct code: + +```sh +read -r "foo[index]" +``` + +### Rationale: + +ShellCheck found an array element passed to read, where the `[]` was not quoted. This means the array index `[index]` will be treated as a glob range, and the word may be replaced or trigger `failglob`. + +In the problematic example, having a directory named `food` will cause the command to become `read -r food` instead, since `food` matches the glob `foo[index]`. The result is assigning a value to the wrong variable. + +Quote or escape the pattern as shown to ensure it always reads into the array `foo` at index `index`. + +### Exceptions: + +None. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file