Similar to Jesse_b's answer, but using a name reference variable instead of variable indirection (requires bash
4.3+):
$ declare -n var=test
$ test="my string"
$ echo "$var"
my string
The name reference variable var
holds the name of the variable it's referencing. When the variable is dereferenced as $var
, that other variable's value is returned.
bash
resolves name references recursively:
$ declare -n var1=var2
$ declare -n var2=test
$ test="hello world"
$ echo "$var1"
hello world
For completeness, using an associative array (in bash
4.0+) is also one way of solving this, depending on requirements:
$ declare -A strings
$ strings[test]="my string"
$ var=test
$ echo "${strings[$var]}"
my string
This provides a more flexible way of accessing more than one value by a key or name that may be determined dynamically. This may be preferable if you want to collect all values of a particular category in a single array, but still be able to access them by some key (e.g. names accessible by ID, or pathnames accessible by purpose etc.) as it does not pollute the variable namespace of the script.
ash
, orbash
, orcsh
, ordash
, ..., orzsh
, or POSIXsh
, or do you need to work across different systems? – Michael Homer Jun 30 '18 at 01:23