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.

2
  • It would be safer to use a case "${VEHICLE_TYPE}" in ... to find the corresponding price Commented Nov 12, 2021 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 Commented Nov 12, 2021 at 11:34

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

That probably won't be a problem but it needs bash >= 4
@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 this is a good answer but a duplicate of stackoverflow.com/a/16553351/7939871
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

1 Comment

@anubhava As a veteran here, I am surprised you forgot to mention this earlier answer: stackoverflow.com/a/18124325/7939871

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.