mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +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:
|
### Problematic code:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
var=(foo bar)
|
name="PATH"
|
||||||
echo "${var[1]}"
|
echo "${!name}"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Correct code:
|
### 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
|
```sh
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
var=(foo bar)
|
name="PATH"
|
||||||
echo "${var[1]}"
|
echo "${!name}"
|
||||||
```
|
```
|
||||||
|
|
||||||
Alternatively, rewrite the logic to use e.g. indirect variable references or `set`:
|
Alternatively, carefully rewrite using `eval`:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -- foo bar
|
name=PATH
|
||||||
echo "$2"
|
eval "echo \"\$$name\""
|
||||||
```
|
```
|
||||||
|
|
||||||
### Rationale:
|
### 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:
|
### Exceptions:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user