2

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.

treyBake
  • 6,440
  • 6
  • 26
  • 57
Karthick
  • 21
  • 1
  • 4

2 Answers2

3

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.

thb
  • 13,796
  • 3
  • 40
  • 68
1

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
Walter A
  • 19,067
  • 2
  • 23
  • 43