Bash – How to Get Values from Variables in Bash Script

bashscripts

I am trying to write a bash script to print values of the 3 variables. Keep getting errors. What am I doing wrong?

INPUT1=/tmp/dir1
INPUT2=/tmp/dir2
INPUT3=/tmp/dir3

for i in 1 2 3
do 
echo $(INPUT$i)
done

When I run this script, tho output is:

syntax error: operand expected (error token is "/tmp/dir1

Best Answer

Bash doesn't support that kind of syntax directly. You could use 'eval', however with modern versions of 'bash' the cleanest way imho is via an array

input=( "/tmp/dir1" "/tmp/dir2" "/tmp/dir3" )

for i in {0,1,2}; do echo "${input[i]}"; done

(note that bash arrays are zero-indexed); or to list all elements you can use

for i in "${input[@]}"; do echo "$i"; done
Related Question