mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2313 (markdown)
29
SC2313.md
Normal file
29
SC2313.md
Normal file
@@ -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!
|
Reference in New Issue
Block a user