Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable list or array structure in Bash? How can I easily append to it?

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?

like image 534
Joe Avatar asked Jan 06 '10 13:01

Joe


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.

How do I append to a variable in bash?

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.

What does %% do in bash?

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.


5 Answers

$ 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[@]})
like image 178
Dennis Williamson Avatar answered Oct 01 '22 14:10

Dennis Williamson


foo=(a b c)
foo=("${foo[@]}" d)
for i in "${foo[@]}"; do echo "$i" ; done
like image 23
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 13:10

Ignacio Vazquez-Abrams


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
like image 26
codaddict Avatar answered Oct 01 '22 15:10

codaddict


$ for i in "string1" "string2" "string3"
> do
> array+=($i)
> done
$ echo ${array[@]}
string1 string2 string3
like image 30
ghostdog74 Avatar answered Oct 01 '22 13:10

ghostdog74


The rather obscure syntax for appending to the end of an array in Bash is illustrated by the following example:

myarr[${#myarr[*]}]="$newitem"
like image 45
ennuikiller Avatar answered Oct 01 '22 14:10

ennuikiller