1

I'm trying to print values of multiple variables that are listed in a Bash array as evident in the minimal code example below.

#!/bin/bash
VAR1="/path/to/source/root"
VAR2="/path/to/target/root"
VAR3="50"

VARS=("VAR1" "VAR2" "VAR3")
for var in ${VARS[*]}; do
    echo "value of $var is ${$var}"
done

This gives me an error

line 8: value of $var is ${$var}: bad substitution

I want the following output:

value of VAR1 is /path/to/source/root
value of VAR2 is /path/to/target/root
value of VAR3 is 50

My search on Google and SO was not very fruitful. Because of the indirection (i.e., var iterates over an array containing names of variables for which I want the values), I'm not able to precisely word my search. But any help is appreciated.

1 Answer 1

2

Use indirect reference as:

#!/bin/bash
VAR1="/path/to/source/root"
VAR2="/path/to/target/root"
VAR3="50"

VARS=("VAR1" "VAR2" "VAR3")
for var in ${VARS[*]}; do
    echo "value of $var is ${!var}"
done

Output:

value of VAR1 is /path/to/source/root
value of VAR2 is /path/to/target/root
value of VAR3 is 50
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.