arrayslinuxbash

Bash: How to declare empty array, and then add variables to it


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.


Solution

  • You declare and add to a bash array as follows:

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

    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 something like:

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