Loop through an array of strings in Bash?

前端 未结 19 2780
情深已故
情深已故 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:20
    listOfNames="db_one db_two db_three"
    for databaseName in $listOfNames
    do
      echo $databaseName
    done
    

    or just

    for databaseName in db_one db_two db_three
    do
      echo $databaseName
    done
    
    0 讨论(0)
  • 2020-11-22 04:21

    I loop through an array of my projects for a git pull update:

    #!/bin/sh
    projects="
    web
    ios
    android
    "
    for project in $projects do
        cd  $HOME/develop/$project && git pull
    end
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-11-22 04:22

    The declare array doesn't work for Korn shell. Use the below example for the Korn shell:

    promote_sla_chk_lst="cdi xlob"
    
    set -A promote_arry $promote_sla_chk_lst
    
    for i in ${promote_arry[*]};
        do
                echo $i
        done
    
    0 讨论(0)
  • 2020-11-22 04:22

    Try this. It is working and tested.

    for k in "${array[@]}"
    do
        echo $k
    done
    
    # For accessing with the echo command: echo ${array[0]}, ${array[1]}
    
    0 讨论(0)
  • 2020-11-22 04:23

    Single line looping,

     declare -a listOfNames=('db_a' 'db_b' 'db_c')
     for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
    

    you will get an output like this,

    db_a
    db_b
    db_c
    
    0 讨论(0)
提交回复
热议问题