Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!