mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC3030 (markdown)
55
SC3030.md
Normal file
55
SC3030.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
## In POSIX sh, arrays are undefined.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
#!/bin/sh
|
||||||
|
x=( foo bar "Hello World" )
|
||||||
|
for word in "${x[@]}"
|
||||||
|
do
|
||||||
|
touch "$word.dat"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
Consider switching to a shell that does support arrays, such as `bash` or `ksh`, by changing the shebang.
|
||||||
|
|
||||||
|
Alternatively, if you only need a single array at a time, you may be able to rewrite to use the positional parameters:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
set -- foo bar "Hello World"
|
||||||
|
for word in "$@"
|
||||||
|
do
|
||||||
|
touch "$word.dat"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
or strings with carefully chosen delimiters:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
x='foo
|
||||||
|
bar
|
||||||
|
Hello World
|
||||||
|
'
|
||||||
|
|
||||||
|
printf '%s' "$x" |
|
||||||
|
while IFS='' read -r word
|
||||||
|
do
|
||||||
|
touch "$word.dat"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
Arrays are specific to Bash and Ksh, but you are using them in a script declared to run with `sh` or `dash`. These shells do not support arrays at all. You should either switch to Bash/Ksh, or rewrite the script to not use arrays.
|
||||||
|
|
||||||
|
There are no great replacements, especially not that can be mechanically applied, but using the positional parameters or a delimited string works in many cases, as shown in the examples.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Related resources:
|
||||||
|
|
||||||
|
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Reference in New Issue
Block a user