2

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.

finepax007
  • 651
  • 3
  • 8
  • 16
  • It would be safer to use a `case "${VEHICLE_TYPE}" in ...` to find the corresponding price – Fravadona Nov 12 '21 at 11:28
  • I want to make things generic with no hardcoding of custom values in script hence passing from outside so that the --vehicletype would be optional param , introducing case would make script tightly coupled CAR_PRICE=50000 BIKE_PRICE=20000 are being read from property file – finepax007 Nov 12 '21 at 11:34

2 Answers2

4

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
dan
  • 4,846
  • 6
  • 15
  • 1
    That probably won't be a problem but it needs bash >= 4 – Fravadona Nov 12 '21 at 11:38
  • 1
    @Fravadona 100% true. However since bash 4.0 was released twelve years ago (2009), I think we're at a point where it's only worth mentioning if the OS is Mac, or the questioner says they're on an older platform. – dan Nov 12 '21 at 12:00
  • @dan this is a good answer but a duplicate of https://stackoverflow.com/a/16553351/7939871 – Léa Gris Nov 12 '21 at 13:17
3

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • @anubhava As a veteran here, I am surprised you forgot to mention this earlier answer: https://stackoverflow.com/a/18124325/7939871 – Léa Gris Nov 12 '21 at 13:21