Bash String concatenation and get content

2020-05-08 06:39发布

问题:

I have a bash loop, I'm trying to read the all variables:

var1="hello1"

var2="hello2"

var3="hello3"

for i in `seq 1 3`;
do
 ab=var$i
 # Now ab == var1, I want to echo $var1 

done

I'm trying to get dynamically var(1)(2)(3) and get out the String of it.

Edit:

The point here is how to concatenation variables like ab=var$i and using the ab variable (var1 for example) as a variable, I mean to get the var1 value hello1 I didn't mean how to do it to this specific example, and not with arrays.

Hope I have clarified myself.

回答1:

var1="hello1"
var2="hello2"
var3="hello3"

for i in `seq 1 3`;
do
    ab=var$i
    echo ${!ab}
done

I'm not sure it is the best solution to your larger problem, but it is the direct solution to your immediate request.



回答2:

Simpler approach:

var1="hello1"
var2="hello2"
var3="hello3"

eval echo\ $var{1..3}\;

Is expanded to:

echo $var1
echo $var2
echo $var3

Ouput:

hello1 
hello2 
hello3


标签: linux bash