0

I have list of parameters that take from a property file looks like that:

db_instanceid=i-0c2b12ae02d454018
db_secgrp=sg-8c2efcf3
backend_instanceid=i-0199621ba358d1814
backend_secgrp=sg-5e508221
frontend_instanceid=i-0199621ba358d1814
frontend_secgrp=sg-e152809e

in bash, I want to use an array to perform actions using those parameters, Something like that:

declare -a arr=("frontend" "backend" "db")
for i in "${arr[@]}"
do
   inter=$i  
   echo "Get PublicIp for $inter server"
   echo "$inter security group - $inter_secgrp" ; 
done

But $inter_secgrp itself will be read as a parameter, so I get an empty string (which make sense). How can I read this parameter the right way so I will get the value of all "secgrp"

needed output:

Get PublicIp for frontendserver
frontendserver security group - sg-e152809e

Get PublicIp for backend
backendsecurity group - sg-5e508221

Get PublicIp for db
dbsecurity group - sg-8c2efcf3
1
  • Looks like eval is a must this time :) Commented Feb 5, 2018 at 9:00

2 Answers 2

3

Could do it with indirect expansion

. parameterfile
declare -a arr=("frontend" "backend" "db")
for inter in "${arr[@]}"
do
   echo "Get PublicIp for $inter server"
   inter_secgrp=${inter}_secgrp
   echo "$inter security group - ${!inter_secgrp}" ;
done
Sign up to request clarification or add additional context in comments.

Comments

0

The temptation to use eval is particularly strong here.

. parameterfile
declare -a arr=("frontend" "backend" "db")
for inter in "${arr[@]}"
do
   echo "Get PublicIp for $inter server"
   eval inter_secgrp=\$${inter}_secgrp
   echo "$inter security group - $inter_secgrp" ;
done

And then $inter_secgrp is what you want.

To be simple, eval tells Bash to evaluate the line for an extra time before executing it. Here after the first evaluation, the eval line turns to (for example

eval inter_secgrp=$db_secgrp

And then things after eval is evaluated again, so $db_secgrp gets expanded, giving what you want.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.