You are not logged in.

#1 2016-10-07 12:16:30

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,597
Website

Using bash store a value to an array in a while loop failing

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 packagesZsh and other configs

Offline

#2 2016-10-07 12:30:56

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: Using bash store a value to an array in a while loop failing

  Arr=["$x"]="$diff"

dude, remove the first =


This silver ladybug at line 28...

Offline

#3 2016-10-07 12:32:28

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,597
Website

Re: Using bash store a value to an array in a while loop failing

lolilolicon wrote:
  Arr=["$x"]="$diff"

dude, remove the first =

<< HEADSMACK >> Thank you!  Works as expected now.


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

#4 2016-10-07 12:36:51

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: Using bash store a value to an array in a while loop failing

"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

Board footer

Powered by FluxBB