Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash array declaration and appending data

I'm trying to declare and append to an array in a bash script, after searching i resulted in this code.

list=()
list+="string"

But when i echo this out it results in nothing. I have also tried appending to the array like this

list[$[${#list[@]}+1]]="string"

I don't understand why this is not working, anyone have any suggestions?


EDIT: The problem is list is appended to inside a while loop.

list=()

git ls-remote origin 'refs/heads/*' | while read sha ref; do
    list[${#list[@]}+1]="$ref"
done

declare -p list

see stackoverflow.com/q/16854280/1126841

like image 317
A.Jac Avatar asked Mar 26 '26 07:03

A.Jac


2 Answers

You can append new string to your array like this:

#!/bin/bash

mylist=("number one")

#append "number two" to array    
mylist=("${mylist[@]}" "number two")

# print each string in a loop
for mystr in "${mylist[@]}"; do echo "$mystr"; done

For more information you can check http://wiki.bash-hackers.org/syntax/arrays

like image 166
Ali Okan Yüksel Avatar answered Mar 28 '26 19:03

Ali Okan Yüksel


Ali Okan Yüksel has written down an answer for the first method you mentioned about adding items in an array.

list+=( newitem  another_new_item ··· )

The right way of the second method you mentioned is:

list[${#list[@]}]="string"

Assuming that a non-sparse array has N items and because bash array indexes starts from 0, the last item in the array is N-1th. Therefore the next item must be added in the N position (${#list[@]}); not necessarily in N+1 as you wrote.

Instead, if a sparse array is used, it is very useful the bash parameter expansion which provides the indexes of the array:

${!list[@]}

For instance,

$ list[0]=3
$ list[12]=32
$ echo ${#list[@]}
2
$ echo ${!list[@]}
0 12
like image 36
Jdamian Avatar answered Mar 28 '26 20:03

Jdamian