Skip to content

Files

Latest commit

 

History

History
54 lines (39 loc) · 980 Bytes

SC2271.md

File metadata and controls

54 lines (39 loc) · 980 Bytes

Pattern: Use of var$n=value

Issue: -

Description

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.

Example of incorrect code:

n=1
var$n="hello"

Example of correct code:

For integer indexing in ksh/bash, consider using an indexed array:

n=1
var[n]="hello"
echo "${var[n]}"

For string indexing in ksh/bash, use an associative array:

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:

n="Foo"
declare "var$n=42"
echo "$varFoo"

For sh, with single line contents, consider read:

n="Foo"
read -r "var$n" << EOF
hello
EOF
echo "$varFoo"

Further Reading