I'm having trouble assigning values to a specific bash index,
but apparently only when the index variable is set using a while read
loop.
Taking this code as a test example:
#!/bin/bash
read -d '' TESTINPUT << 'EOF'
1,100
2,200
8,300
EOF
declare -A ARRAY
echo "$TESTINPUT"| while read _l; do
i=$(cut -d, -f1 <<< $_l)
j=$(expr $i + 0)
value=$(cut -d, -f2 <<< $_l)
ARRAY[$j]=$value
done
for i in {4..6}; do
ARRAY[$i]=$i
done
for i in {1..10}; do
echo "$i ${ARRAY[$i]}"
done
The output clearly shows that in the case of the while loop, the array variables don't get set,
while with the for loop, using a range of {4..6}
doesn't seem to have any issue.
$ ./test_array.sh
1
2
3
4 4
5 5
6 6
7
8
9
10
Notice I also tried to convert the index variable to an integer using
j=$(expr $i + 0)
But that doesn't seem to work either.
Any ideas?
shopt -s lastpipe
or rearrange that to not use a pipe.echo foo | blah
could be replaced withblah <<< foo
IFS=, read -r a b
to split the fields without runningcut
. Also, Bash doesn't really have types for variables, so$(expr $i + 0)
probably doesn't do anything (except it would remove leading zeroes). If you have just integer indexes, you could use a regular, non-associative array,declare -a
instead of-A
. Though note that leading zeroes would make Bash interpret the numbers as octal.