3

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.

3
  • 1
    I can't find a answer to this problem, other than people asking to use an array instead. That's because you should use an array instead. Commented Jan 27, 2016 at 15:09
  • I would use an array for that. Commented Jan 27, 2016 at 15:16
  • Yes, use an array or see Bash FAQ 006 if you really want to do this without it. Commented Jan 27, 2016 at 15:30

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.