I am trying to do the following in my script:
#/bin/bash -x var1=www var2=www2 var3=www3 var4=www4 for i in 1 2 3 4; do echo $var$i done
Obviously, this doesn’t work as expected and results in the following output:
$var1 $var2 $var3 $var4
How can I dynamically reference the variables in my loop?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Are you looking for this?
$ cat indirection.bash
#!/bin/bash -x
var1=www
var2=www2
var3=www3
var4=www4
for i in 1 2 3 4; do
s="var${i}"
echo "${!s}"
done
$ ./indirection.bash www www2 www3 www4
Method 2
You could use an array:
#/bin/bash -x
declare -a vars=(
www
www2
www3
www4
)
for var in "${vars[@]}"; do
echo "$var"
done
Or iterate with index:
for i in "${!vars[@]}"; do
echo "${vars[$i]}"
done
Method 3
Normally shell expands variable only once. You can use indirect expand or ask shell to expand it one more time, for example:
eval "val=$var$i"; echo "$val";
instead of just:
echo "$var$i"
This method is very portable, but uses evil eval.
Using indirect expansion as shown in other answers (see Parameter Expansion in man bash) ${!VAR_NAME} is a good solution, when portability is not necessary and you are allowed to use BASH extensions.
Method 4
Use an associative array. There’s no good reason to generate variable names like this.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0