Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append elements to an array in bash

Tags:

arrays

bash

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

Any help would be appreciated.

like image 513
Steve J Avatar asked Mar 23 '19 18:03

Steve J


People also ask

How do I append to an array in bash?

To append element(s) to an array in Bash, use += operator.

How do I append to a list in bash?

Using shorthand operators is the simplest way to append an element at the end of an array. In the following script, an array with 6 elements is declared. Next '+=' shorthand operator is used to insert a new element at the end of the array. 'for' loop is used here to iterate the array and print the array elements.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.


1 Answers

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
like image 67
wjandrea Avatar answered Sep 22 '22 15:09

wjandrea