mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2271 (markdown)
65
SC2271.md
Normal file
65
SC2271.md
Normal file
@@ -0,0 +1,65 @@
|
||||
## For indirection, use arrays, `declare "var$n=value"`, or (for sh) read/eval
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
n=1
|
||||
var$n="hello"
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
For integer indexing in ksh/bash, consider using an indexed array:
|
||||
|
||||
```sh
|
||||
n=1
|
||||
var[n]="hello"
|
||||
echo "${var[n]}"
|
||||
```
|
||||
|
||||
For string indexing in ksh/bash, use an associative array:
|
||||
|
||||
```sh
|
||||
typeset -A var
|
||||
n="greeting"
|
||||
var[$n]="hello"
|
||||
echo "${var[$n]}"
|
||||
```
|
||||
|
||||
If you actually need a variable with the constructed name in bash, use `declare`:
|
||||
|
||||
```sh
|
||||
n="Foo"
|
||||
declare "var$n=42"
|
||||
echo "$varFoo"
|
||||
```
|
||||
|
||||
For `sh`, with single line contents, consider `read`:
|
||||
```sh
|
||||
n="Foo"
|
||||
read -r "var$n" << EOF
|
||||
hello
|
||||
EOF
|
||||
echo "$varFoo"
|
||||
```
|
||||
|
||||
or with careful escaping, `eval`:
|
||||
|
||||
```sh
|
||||
n=Foo
|
||||
eval "var$n='hello'"
|
||||
echo "$varFoo"
|
||||
```
|
||||
|
||||
### Rationale:
|
||||
|
||||
`var$n=value` is not a valid way of assigning to a dynamically created variable name in any shell. Please use one of the other methods to assign to names via expanded strings. [Wooledge BashFaq #6](https://mywiki.wooledge.org/BashFAQ/006) has significantly more information on the subject.
|
||||
|
||||
|
||||
### Exceptions:
|
||||
|
||||
None
|
||||
|
||||
### Related resources:
|
||||
|
||||
* [Wooledge BashFaq #6](https://mywiki.wooledge.org/BashFAQ/006): How can I use variable variables (indirect variables, pointers, references) or associative arrays?
|
Reference in New Issue
Block a user