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 https://mcmap.net/q/45717/-a-variable-modified-inside-a-while-loop-is-not-remembered/1126841
echo "${list[0]}"
– Fraze$list
and${list[0]}
are effectively equivalent.list+="string"
won't addstring
to the array, but it will appendstring
to the end of the first element of the array (creating said element if necessary). – Chiefly$[...]
is obsolete (use$((...))
instead) and unnecessary; the index of a regular array is automatically evaluated in an arithmetic context, solist[${#list[@]}+1]="string"
would be sufficient. – Chieflydeclare -p list
. If it is an array will be printed likedeclare -a list=<values>.
– Demarcatelist[${#list[@]}+1]="string"
anddeclare -p list
it results indeclare -a list='()'
– Spermiogenesisdeclare -a list='([1]="string")'
. – Chiefly