29

I tried the += operator to append an array in bash but do not know why it did not work

#!/bin/bash

i=0
args=()
while [ $i -lt 5 ]; do
    args+=("${i}")
    echo "${args}"
    let i=i+1
done

expected results

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

actual results

0
0
0
0
0
4
  • 2
    Please take a look: shellcheck.net Commented Mar 23, 2019 at 18:14
  • 3
    It does work. However, echo "${args}" only shows the first element. You need to change it to echo "${args[@]}" to output all elements Commented Mar 23, 2019 at 18:15
  • 1
    Slightly OT, but i=0 ... while [ $i -lt 5 ]; do ... let i=i+1 ... done can be replaced with for ((i=0; i<5; ++i)); do ... done Commented Mar 23, 2019 at 18:17
  • Possible duplicate: Expanding a bash array only gives the first element Commented Oct 17, 2022 at 20:43

2 Answers 2

41

It did work, but you're only echoing the first element of the array. Use this instead:

echo "${args[@]}"

Bash's syntax for arrays is confusing. Use ${args[@]} to get all the elements of the array. Using ${args} is equivalent to ${args[0]}, which gets the first element (at index 0).

See ShellCheck: Expanding an array without an index only gives the first element.

Also btw you can simplify let i=i+1 to ((i++)), but it's even simpler to use a C-style for loop. And also you don't need to define args before adding to it.

So:

#!/bin/bash
for ((i=0; i<5; ++i)); do
    args+=($i)
    echo "${args[@]}"
done
Sign up to request clarification or add additional context in comments.

Comments

0

I think this is more what you're looking for ...

#! /bin/bash

for (( i = 1; i <= ${#@}; i++ ))
do
  args[${i}]="${!i}"
done

for (( i = 1; i <= ${#args[@]}; i++ ))
do
  echo "${args[${i}]}"
done
1 2 3
4 5 6

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.