26

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Steve J
  • 263
  • 1
  • 3
  • 4

2 Answers2

37

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0
#!/bin/bash
for ((i=0; i<5; ++i)); do
  args+=($i)
  echo "${args[@]}"
done
$ ./run.sh "1 2 3" "4 5 6"
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

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
    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](/help/how-to-answer). – Community Mar 30 '23 at 08:26