I'm trying to collect string values in a bash script. What's the simplest way that I can append string values to a list or array structure such that I can echo them out at the end?
To append element(s) to an array in Bash, use += operator.
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.
The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.
In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.
$ arr=(1 2 3)
$ arr+=(4)
$ echo ${arr[@]}
1 2 3 4
Since Bash uses sparse arrays, you shouldn't use the element count ${#arr}
as an index. You can however, get an array of indices like this:
$ indices=(${!arr[@]})
foo=(a b c)
foo=("${foo[@]}" d)
for i in "${foo[@]}"; do echo "$i" ; done
To add to what Ignacio has suggested in another answer:
foo=(a b c)
foo=("${foo[@]}" d) # push element 'd'
foo[${#foo[*]}]="e" # push element 'e'
for i in "${foo[@]}"; do echo "$i" ; done
$ for i in "string1" "string2" "string3"
> do
> array+=($i)
> done
$ echo ${array[@]}
string1 string2 string3
The rather obscure syntax for appending to the end of an array in Bash is illustrated by the following example:
myarr[${#myarr[*]}]="$newitem"
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