简体   繁体   中英

How to add called variable as a suffix to another variable and then call the suffixed variable?

My script:

for (( i=1; i <= $j; i++ ))
do
list_$i = $i
echo "$list_$i"
done

Expected output:

1
2
3
.
.
.
etc

I have a problem with the echo statement while calling the variable.

Please help me on this.

Assuming that $j has an nonnegative integral value,

for (( i=1; $i<=$j; i=$i+1 ))
do
    list[$i]=$i
    echo "${list[$i]}"
done

Bash arrays are used, whereby $list is a single structure, a Bash array.

First remember that a variable assignment is without spaces around the = .
What you are trying to do, is possible but complicated.

for (( i=1; i <= 6; i++ )); do 
   source <(echo "list_$i=$i")
   varname=list_$i
   echo "${!varname}"
done

You can also view the results in a different loop

for result in list_{1..6}; do
   echo "${result}=${!result}"
done

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