0

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.
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
xavi
  • 109
  • 6
  • `var2` and `var5` aren't generated either. The syntax for variable assignment is `NAME=VALUE`. Parameter expansion comes later into play, and since `var$i` is not a valid variable name, you get a similar error as if you had written `var,i=value`. You could do an `eval var$i="number is $i"`, if you feel you **have** to create a variable like this, but in most cases, designing your script in a different way would be the better solution. – user1934428 Nov 24 '20 at 14:03

3 Answers3

1

You cannot use variable names with a number in it like that: you really need to say:

var1=1
var2=2
var3=3
var4=4
var5=5

Another approach is the usage of arrays.

As far as increasing is concerned (this is not part of the question, but I give is anyways), you might use something like this:

Prompt> var1=1
Prompt> var2=$((var1+1))
Prompt> echo $var2
2

(Mind the double brackets for making calculations)

Dominique
  • 16,450
  • 15
  • 56
  • 112
0
  1. "var1=number is 1" command not found because that's not a command. For example, you can write:
for i in `seq 5`; do
  echo var$i="number is $i"
done

And the output would look like

var1=number is 1
var2=number is 2
var3=number is 3
var4=number is 4
var5=number is 5
  1. The variables have not been generated, you can't just dynamically generate variables. Try to use arrays
Andrii Syd
  • 308
  • 5
  • 15
0

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.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18