creating variable using variable value as part of new variable name
22,785
Solution 1
Use eval
:
filemsgCICS=foo
word1=CICS
eval "echo \"\$filemsg$word1\"" # => foo
eval "filemsg$word1=bar"
echo "$filemsgCICS" # => bar
but think twice if you really need it this way.
Another way in ksh93
is to use namerefs:
word1=CICS
nameref v=filemsg$word1
v="xxx"
echo "$filemsgCICS" # => xxx
For even more nasty hacks like that look here.
Solution 2
export
does this far more safely than does eval
because there is no danger of it executing shell code following a shell token. But it does export
the variables so you can take it as you will.
export "filemsg$word1= "
Solution 3
It's not POSIX, but in bash
there's always printf -v
, which prints not to standard output, but rather to whatever variable name follows -v
:
x=foo; printf -v $x bar; echo $foo
Output:
bar
Solution 4
Try this
let filemsg"$word1"=" "
This may not be the best solution, but it has worked for me in the past.
Author by
dazedandconfused
Updated on September 18, 2022Comments
-
dazedandconfused almost 2 years
I'm trying to create a new variable using the value of an existing variable as part of the variable name.
filemsg"$word1"=" "
I've also tried
filemsg$word1=" " filemsg${word1}=" "
on all attempts I get the following when that line executes,
cicserrors.sh[45]: filemsgCICS= : not found [No such file or directory]
-
Stéphane Chazelas over 10 yearsYou may want to use hashes/associative arrays instead (or
perl
or other real programming language)
-
-
Denis Loh over 10 years@dazedandconfused: Naming variables on the fly is the sort of thing that will have programmers and code maintainers waiting for you in a dark alley for the purposes of beating you with surplus power cords. It's really not a best practice.
-
MariusMatutiae over 10 yearsI agree with @Satanicpuppy: it is a practice to discourage, in my opinion.
-
G-Man Says 'Reinstate Monica' over 5 yearsOK, that lets you display the value of the variable, but the question asks how to create the variable (i.e., to assign / set the value).