Bash for loop to set a variable, its value, and ev

2020-03-27 08:52发布

问题:

How do I use a for loop to define a variable, and its value, and be able to evaluate it?

I can't figure out the evaluation part, but using the for loop to define the variable and its value seems to work. Specifically,

for i in {1..4}
do
    export my${i}var="./path${i}_tofile"
   # or
   # export my${i}var=./path${i}_tofile
   # or
   # eval "my${i}var=\"./path${i}_tofile\""
    echo $[my${i}var]
done

The echo does not evaluate correctly, but the shell does correctly create the variable and the value.

echo $my1var

returns

./path1_tofile

But I need to evaluate the variables using the $i as part of their names.

回答1:

You should instead use an array variable:

declare -a myvar
for i in {1..4}
do
    myvar[$i]="./path${i}_tofile"
done

More details: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html



回答2:

This is how it gets complicated if you don't use an array:

for i in {1..4}
do
    declare my${i}var="./path${i}_tofile"
    tmpvar=my${i}var             # temporary variabled needed for...
    echo "$tmpvar=${!tmpvar}"    # bash indirect variable expansion
done


回答3:

Just replace the echo you are using with:

v=my${i}var
echo ${!v}

Then, the script:

#!/bin/bash

for i in {1..4}
do
    export my${i}var="./path${i}_tofile"
    v=my${i}var
    echo ${!v}
done

Will execute as:

$ ./script
./path1_tofile
./path2_tofile
./path3_tofile
./path4_tofile

But, honestly, working with indirect variables is never easy.
Please consider using Indexed arrays (in this use case even normal arrays will work):

declare -A myvar

for i in {1..4}
do
    myvar[i]="./path${i}_tofile"
    echo "${myvar[i]}"
done


标签: bash shell