5

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]
  • 4
    You may want to use hashes/associative arrays instead (or perl or other real programming language) – Stéphane Chazelas Nov 1 '13 at 13:18
9

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.

  • 2
    @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. – Satanicpuppy Nov 1 '13 at 14:10
  • I agree with @Satanicpuppy: it is a practice to discourage, in my opinion. – MariusMatutiae Nov 1 '13 at 16:11
3

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= "
2

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
1

Try this

let filemsg"$word1"=" "

This may not be the best solution, but it has worked for me in the past.

0

Try this:

word1=CICS

var_name=filemsg$word1

eval ${var_name}="var_value"

To test:

echo $filemsgCICS ==> var_value
-1

Try this:

filemsgCICS=foo

word1=CICS

ref_filemsg=filemsg$word1

echo ${!ref_filemsg} => foo
  • 1
    OK, 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). – G-Man Sep 26 '18 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.