Updated SC3053 (markdown)

Vidar Holen
2020-09-01 17:34:25 -07:00
parent f1ff88bdb0
commit 44b7c2cbf8

@@ -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: