mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 11:19:45 +08:00
Updated SC3053 (markdown)
22
SC3053.md
22
SC3053.md
@@ -1,36 +1,36 @@
|
||||
## In POSIX sh, array references are undefined.
|
||||
## In POSIX sh, indirect expansion is undefined.
|
||||
|
||||
(or "In dash, ... are not supported." when using `dash`)
|
||||
(or "In dash, ... is not supported." when using `dash`)
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
var=(foo bar)
|
||||
echo "${var[1]}"
|
||||
name="PATH"
|
||||
echo "${!name}"
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
The easiest solution is to switch to a shell that does support arrays, like `bash`:
|
||||
The easiest solution is to switch to a shell that does support indirect expansion, like `bash`:
|
||||
|
||||
```sh
|
||||
#!/bin/bash
|
||||
var=(foo bar)
|
||||
echo "${var[1]}"
|
||||
name="PATH"
|
||||
echo "${!name}"
|
||||
```
|
||||
|
||||
Alternatively, rewrite the logic to use e.g. indirect variable references or `set`:
|
||||
Alternatively, carefully rewrite using `eval`:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
set -- foo bar
|
||||
echo "$2"
|
||||
name=PATH
|
||||
eval "echo \"\$$name\""
|
||||
```
|
||||
|
||||
### Rationale:
|
||||
|
||||
Arrays are supported in `bash` and `ksh`, but not in `dash` or POSIX `sh`. Either switch to a shell that supports them, or rewrite your script without relying on arrays. This may not be straight forward.
|
||||
Indirection expansion is an extension in `bash` and `ksh`, and not supported in `dash` or POSIX `sh`. Either switch to a shell that supports them, or write around it with careful use of `eval`. Take care to validate the variable name to avoid fragility and code injection.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
|
Reference in New Issue
Block a user