You are not logged in.
Goal: have the script store a value in a growing array.
Expected result: Create an array with 5 members, in this test case they are all the same value of 123 but they should be stored once per pass through the loop.
Actual result: An array with only 1 member is defined.
#!/bin/bash
x=0
limit=5
while [[ "$x" -lt "$limit" ]]; do
diff=123
Arr=["$x"]="$diff"
echo "Index $x has value ${Arr[$x]}"
x=$(( x + 1 ))
done
echo "${#Arr[@]}"
Result:
% ./arr
Index 0 has value [0]=123
Index 1 has value
Index 2 has value
Index 3 has value
Index 4 has value
1
Why am I not getting 5 members?
Last edited by graysky (2016-10-07 12:31:16)
CPU-optimized Linux-ck packages @ Repo-ck • AUR packages • Zsh and other configs
Offline
Arr=["$x"]="$diff"
dude, remove the first =
This silver ladybug at line 28...
Offline
Arr=["$x"]="$diff"
dude, remove the first =
<< HEADSMACK >> Thank you! Works as expected now.
CPU-optimized Linux-ck packages @ Repo-ck • AUR packages • Zsh and other configs
Offline
"Better" version:
#!/bin/bash
declare -a Arr
limit=5
for ((x=0; x<limit; ++x)); do
diff=123
Arr[x]=$diff
echo "Index $x has value ${Arr[x]}"
done
Note the indexed array subscript [x], like variables in (()), they undergo arithmetic expansion, so no need to write it as [$x].
Last edited by lolilolicon (2016-10-07 12:42:21)
This silver ladybug at line 28...
Offline