7

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]
Braiam
  • 35,991
dazedandconfused
  • 161
  • 2
  • 2
  • 5

6 Answers6

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.

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

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= "
mikeserv
  • 58,310
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
agc
  • 7,223
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:

filemsgCICS=foo

word1=CICS

ref_filemsg=filemsg$word1

echo ${!ref_filemsg} => foo
0

Try this:

word1=CICS

var_name=filemsg$word1

eval ${var_name}="var_value"

To test:

echo $filemsgCICS ==> var_value