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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With