user2107349 user2107349 - 4 years ago 161
Linux Question

Bash for loop on variable numbers

I have a situation where I have large number of numbered variables. I want to evaluate each variable and set variable to a specific string if the condition is matched.

#!/bin/bash
var1=""
var2="1233123213"
var3="22332323222324242"
var4=""
var5=""

for i in 1 2 3 4 5
do
if [ -z "$var{$}i" ]
then
var{$}i="None"
fi
echo "var{$}i \r"
done


but the problem is when I run the script I get following.

{1} \r
{2} \r
{3} \r
{4} \r
{5} \r


How I can fix this.

Answer Source

Use indirect variable expansion in bash with syntax {!var}.

From the man bash page,

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exclamation point must immediately follow the left brace in order to introduce indirection.

Modify your code to something like below,

for i in 1 2 3 4 5
do
     var="var$i"
     [ -z "${!var}" ] && declare "var$i"="none"
done

printf "var1=%s\n" "$var1"
printf "var2=%s\n" "$var2"
printf "var3=%s\n" "$var3"
printf "var4=%s\n" "$var4"
printf "var5=%s\n" "$var5"

The syntax "${!var}" in this case evaluates the value of the variable within the string var which is var1, var2, var3... and the declare syntax sets the variable value at run-time, only for those variables that are empty. Now on printing those variables produces,

var1=none
var2=1233123213
var3=22332323222324242
var4=none
var5=none
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download