Home > OS >  Dynamic Variable assignmenet in ShellScript - How to?
Dynamic Variable assignmenet in ShellScript - How to?

Time:11-12

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

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.

CodePudding user response:

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

CodePudding user response:

You can use price=${VEHICLE_TYPE}_PRICE; echo "${!price}". However, associative arrays are a better tool for this job:

declare -A vehicle_price
vehicle_price[ford]=7777
vehicle_price[toyota]=8888

vehicle_type=toyota
echo "${vehicle_price[$vehicle_type]}"
# gives
8888
  • Related