Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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]
share|improve this question
3  
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

2 Answers 2

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.

share|improve this answer
    
Thanks. That got it working nicely. –  dazedandconfused Nov 1 '13 at 13:37
1  
@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

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= "
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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