Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash declaring variable with a number inside a for loop [duplicate]

I can't find an answer to this problem, other than people asking to use an array instead. That's not what I want. I want to declare a number of variables inside a for loop with the same name except for an index number.

I=0
For int in $ints;
Do i=[$i +1]; INTF$i=$int; done

It doesn't really work. When I run the script it thinks the middle part INTF$i=$int is a command.

like image 819
Raker Avatar asked Mar 18 '26 01:03

Raker


2 Answers

Without an array, you need to use the declare command:

i=0
for int in $ints; do
    i=$((i +1))
    declare "intf$i=$int"
done

With an array:

intf=()
for int in $ints; do
    intf+=( $int )
done
like image 183
chepner Avatar answered Mar 20 '26 13:03

chepner


Bash doesn't handle dynamic variable names nicely, but you can use an array to keep variables and results.

[/tmp]$ cat thi.sh 
#!/bin/bash
ints=(data0 data1 data2)
i=0
INTF=()
for int in $ints
do
 ((i++))
 INTF[$i]=$int
 echo "set $INTF$i INTF[$i] to $int"
done
[/tmp]$ bash thi.sh
set 1 INTF[1] to data0
like image 21
Calvin Taylor Avatar answered Mar 20 '26 13:03

Calvin Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!