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.

Biffen
  • 6,249
  • 6
  • 28
  • 36
Raker
  • 344
  • 2
  • 6
  • 15
  • 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. – 123 Jan 27 '16 at 15:09
  • I would use an array for that. – hek2mgl Jan 27 '16 at 15:16
  • Yes, use an array or see [Bash FAQ 006](http://mywiki.wooledge.org/BashFAQ/006) if you really want to do this without it. – Etan Reisner Jan 27 '16 at 15:30

2 Answers2

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
chepner
  • 497,756
  • 71
  • 530
  • 681
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
Calvin Taylor
  • 664
  • 4
  • 15