Loop through an array of strings in Bash?

前端 未结 19 2789
情深已故
情深已故 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:10

    Implicit array for script or functions:

    In addition to anubhava's correct answer: If basic syntax for loop is:

    for var in "${arr[@]}" ;do ...$var... ;done
    

    there is a special case in bash:

    When running a script or a function, arguments passed at command lines will be assigned to $@ array variable, you can access by $1, $2, $3, and so on.

    This can be populated (for test) by

    set -- arg1 arg2 arg3 ...
    

    A loop over this array could be written simply:

    for item ;do
        echo "This is item: $item."
      done
    

    Note that the reserved work in is not present and no array name too!

    Sample:

    set -- arg1 arg2 arg3 ...
    for item ;do
        echo "This is item: $item."
      done
    This is item: arg1.
    This is item: arg2.
    This is item: arg3.
    This is item: ....
    

    Note that this is same than

    for item in "$@";do
        echo "This is item: $item."
      done
    

    Then into a script:

    #!/bin/bash
    
    for item ;do
        printf "Doing something with '%s'.\n" "$item"
      done
    

    Save this in a script myscript.sh, chmod +x myscript.sh, then

    ./myscript.sh arg1 arg2 arg3 ...
    Doing something with 'arg1'.
    Doing something with 'arg2'.
    Doing something with 'arg3'.
    Doing something with '...'.
    

    Same in a function:

    myfunc() { for item;do cat <<<"Working about '$item'."; done ; }
    

    Then

    myfunc item1 tiem2 time3
    Working about 'item1'.
    Working about 'tiem2'.
    Working about 'time3'.
    

提交回复
热议问题