Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic Variable assignmenet in ShellScript – How to?

I have two variables in my bash script

CAR_PRICE=50000
BIKE_PRICE=20000

I am passing a command line argument while executing my .sh shell script file.

--vehicletype CAR  or --vehicletype BIKE

I am able to read the vehicletype value in the script and store in another varible

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

VEHICLE_TYPE=<VALUE PASSED FROM COMMAND LINE ARG i.e CAR/BIKE

Now I am trying to dynamically read CAR_PRICE or BIKE_PRICE using following syntax

${${VEHICLE_TYPE}_PRICE} 

to get the values of the params subtituting the first part of the variable
dynamically based on the value passwed ie but it is throwing Bad Substitution error.

I tried several ways but nothing seem to work. I am new to shell script and not sure if such
dynamic substitution is supported in bash script.

Any pointers would be helpful.

>Solution :

You can use indirect variable reference in bash:

CAR_PRICE=50000
BIKE_PRICE=20000
VEHICLE_TYPE='CAR'
var="${VEHICLE_TYPE}_PRICE"

# variable name
echo "$var"
# variable value
echo "${!var}"

Output:

CAR_PRICE
50000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading