0

I have multiple variables in a shell script; i was trying to save some code duplication and wanted to do something like following

# variables
FLAG=SIM
SIM_ICR_KEY_VAL="http://www.example.com/simi/icr"
REAL_ICR_KEY_VAL="http://www.example.com/real"

Based on the FLAG value i want to access the correct variable (without using IF's) When i try this it echos the variable name & not the value itself.

 echo $(echo ${FLAG}_ICR_KEY_VAL)

On further note; i need to use these substitutions inline in a sed statememt:

sed "s!${ISTR_KEY}=.*!${ISTR_KEY}=${SIM_ISTR_KEY_VAL}!" > tmp.file

... i am not sure its possible or not, please suggest

2 Answers 2

2

Reflection can be achieved with the infamous eval:

eval thisvar=\$${FLAG}_INC_KEY_VAL;
echo "We are using $thisvar"

Whenever you find yourself dynamically synthesizing a variable name, though, you are probably Doing It Wrong. You should consider alternatives like arrays:

ICR_KEY_VAL[0]="http://www.example.com/simi/icr"
ICR_KEY_VAL[1]="http://www.example.com/real"

SIM=0

echo ${ICR_KEY_VAL[$SIM]}
1
  • @sid: Glad to hear -- never give up believing in the power of the shell! :-)
    – Kerrek SB
    Feb 19, 2012 at 23:28
0

I don't know how to do it directly, but in bash you can do it indirectly:

FLAG=SIM
SIM_ICR_KEY_VAL="http://www.example.com/simi/icr"
REAL_ICR_KEY_VAL="http://www.example.com/real"
FLAG_ICR_KEY_VAL=${FLAG}_ICR_KEY_VAL
sed "s!${ISTR_KEY}=.*!${ISTR_KEY}=${!FLAG_ISTR_KEY_VAL}!" > tmp.file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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