Search code examples
bashvariablesincrementvariable-names

Increment variable name results in command not found


I am trying to increment a variable name based on the input and call the value after the loop is done.

for i in `seq 5`; do
  var$i="number is $i"
done
 echo $var2 $var5

Results in

./test.sh: line 4: var1=number is 1: command not found
./test.sh: line 4: var2=number is 2: command not found
./test.sh: line 4: var3=number is 3: command not found
./test.sh: line 4: var4=number is 4: command not found
./test.sh: line 4: var5=number is 5: command not found

There are 2 things I don't understand:

  1. "var1=number is 1" is understood as a command.
  2. var2 and var5 are actually generated but they are not displayed outside of the loop.

Solution

  • To achieve the outcome required, the use of arrays are needed and so:

    #!/bin/bash
    for i in $(seq 5)
    do
      var[$i]="number is $i"
    done
    for i in "${var[@]}"
    do
        echo "$i"
    done
    

    Set the index and values for the array var accordingly and then loop through the array and print the values.