7

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.

5
  • 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 Commented Mar 30, 2020 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 minimal reproducible example definition). Commented Mar 30, 2020 at 23:22
  • BTW, in general, for i in $(seq 0 $unknown) would be better written as for ((i=0; i<unknown; i++)). seq is not a standardized command or part of the shell itself, and running an external command when not needed is generally inefficient. (The POSIX-compliant alternative is wordier: i=0; while [ "$i" -lt 10 ]; do ...; i=$((i + 1)); done -- there's a reason ksh and bash provide the shorter form). Commented Mar 30, 2020 at 23:24
  • Thanks, Charles Duffy. I'm learning as I go... Commented Mar 30, 2020 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. Commented Mar 30, 2020 at 23:29

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.