简体   繁体   中英

Bash String concatenation and get content

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM