4

I was hoping a kind person more intelligent than me could help me out here.

I am working on a Bash script, and in it there is a for loop that will go around an unknown/undefined number of times.

Now, in this for loop, there will be a value assigned to a variable. Let's call this variabe: $var1

Each time the loop goes (and I will never know how many times it goes), I would like to assign the value inside $var1 to an array, slowly building up the array as it goes. Let's call the array $arr

This is what I have so far:

for i in $( seq 0 $unknown ); do
    ...
    some commands that will make $var1 change...
    ...

    arr=("${arr[@]}" "$var1")
done

However, when I want to echo or use the values in the array $arr, I get no results

Perhaps someone will kindly help me in the right direction?

I would really appreciate it so much.

etsnyman
  • 255
  • 3
  • 8
  • 2
    `arr+=("$var1")` will populate the array inside the loop, and if you really want to define an empty array before/outside the loop, `arr=()` Or `declare -a arr` – Jetchisel Mar 30 '20 at 23:07
  • Show us how you're trying to use the values in the array, and ensure that you're providing not pseudocode but a working example we can run ourselves without needing to make any changes to see your problem (as described in the [mre] definition). – Charles Duffy Mar 30 '20 at 23:22
  • BTW, in general, `for i in $(seq 0 $unknown)` would be better written as `for ((i=0; i – Charles Duffy Mar 30 '20 at 23:24
  • Thanks, Charles Duffy. I'm learning as I go... – etsnyman Mar 30 '20 at 23:27
  • 1
    I've voted to re-open this - it appears to me that, while the proposed dupe was *related* to arrays, it was a totally *different* question regarding why `echo ${arr}` only ever gave the first element. – paxdiablo Mar 30 '20 at 23:29

1 Answers1

4

You declare and add to a bash array as follows:

declare -a  arr       # or arr=()
arr+=("item1")
arr+=("item2")

Simple as that.

After executing that code, the following assertions (among others) are true:

${arr[@]}  == item1 item2
${#arr[@]} == 2
${arr[1]}  == item2

In terms of the code you provided, you would use:

declare -a arr
for i in $( seq 0 $unknown ); do
    ...
    some commands that will make $var1 change...
    ...

    arr+=("$var1")
done
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953