2

I just need to create an incremental var name inside a loop. The variable must use "in the var name the number of the cycle".

Example inside a loop:

# on Cycle=1
MyVar$Cycle=Exec$Cycle   # (equal to MyVar1=Exec1)

# on Cycle=2
MyVar$Cycle=Exec$Cycle   # (equal to MyVar2=Exec2)

# etc...

So how can I correctly set the var name?

In batching works easely:

set MyVar%Cycle%=Exec%Cycle% ...

But I don't know how to make it happen in Bash.

Of course tying like this MyVar$Cycle=Exec$Cycle do not work.

Just need to be able to set that incremental varname so I can give to them the values i may need time by time. For me, the script is working all good but the set of a new var name in real time don't.

2

1 Answer 1

2

One possible way to solve this task is to use the command eval in a way as this:

#!/bin/bash

for i in {1..5}
do
        eval "var$i"="$i"
done

# Output the result
for i in {1..5}
do
        echo -n "\$var$i : "
        eval echo "\$var$i"
done

Sample output:

$ ./cycle.sh
$var1 : 1
$var2 : 2
$var3 : 3
$var4 : 4
$var5 : 5

However, I think it is better to adapt your scrip to works with arrays in order to avoid such magics:

#!/bin/bash

for i in {1..5}
do
        array["$i"]="$i"
done

# Output the result
for i in {1..5}
do
        echo "\$array[$i]" : "${array[$i]}"
done

Sample output:

$ ./cycle.sh
$array[1] : 1
$array[2] : 2
$array[3] : 3
$array[4] : 4
$array[5] : 5
  • Note: by default the first index within a Bash array is [0], not [1].
2
  • Thanks so much, you just gave me the right answer and i now can finally go ahead "Translating" a batch script into sh. Thanks
    – MauSH
    Jan 9, 2020 at 13:03
  • 2
    @MauSH please note that sh is not bash. What sh is will depend on the system you are using. On Ubuntu it is a minimal shell called dash. This solution will not work with sh (or dash) but works with bash.
    – terdon
    Jan 9, 2020 at 13:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .