Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an array of strings in Bash?

Tags:

arrays

bash

shell

I want to write a script that loops through 15 strings (array possibly?) Is that possible?

Something like:

for databaseName in listOfNames then   # Do something end 
like image 766
Mo. Avatar asked Jan 16 '12 13:01

Mo.


People also ask

How do I loop through an array in bash?

There are two ways to iterate over items of array using For loop. The first way is to use the syntax of For loop where the For loop iterates for each element in the array. The second way is to use the For loop that iterates from index=0 to index=array length and access the array element using index in each iteration.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.


1 Answers

You can use it like this:

## declare an array variable declare -a arr=("element1" "element2" "element3")  ## now loop through the above array for i in "${arr[@]}" do    echo "$i"    # or do whatever with individual element of the array done  # You can access them using echo "${arr[0]}", "${arr[1]}" also 

Also works for multi-line array declaration

declare -a arr=("element1"                  "element2" "element3"                 "element4"                 ) 
like image 138
anubhava Avatar answered Oct 23 '22 11:10

anubhava