Loop through an array of strings in Bash?

前端 未结 19 2821
情深已故
情深已故 2020-11-22 03:59

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

Something like:

for databaseName in listOfNames
then
  # D         


        
19条回答
  •  遥遥无期
    2020-11-22 04:22

    Surprised that nobody's posted this yet -- if you need the indices of the elements while you're looping through the array, you can do this:

    arr=(foo bar baz)
    
    for i in ${!arr[@]}
    do
        echo $i "${arr[i]}"
    done
    

    Output:

    0 foo
    1 bar
    2 baz
    

    I find this a lot more elegant than the "traditional" for-loop style (for (( i=0; i<${#arr[@]}; i++ ))).

    (${!arr[@]} and $i don't need to be quoted because they're just numbers; some would suggest quoting them anyway, but that's just personal preference.)

提交回复
热议问题