Loop through an array of strings in Bash?

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

    In the same spirit as 4ndrew's answer:

    listOfNames="RA
    RB
    R C
    RD"
    
    # To allow for other whitespace in the string:
    # 1. add double quotes around the list variable, or
    # 2. see the IFS note (under 'Side Notes')
    
    for databaseName in "$listOfNames"   #  <-- Note: Added "" quotes.
    do
      echo "$databaseName"  # (i.e. do action / processing of $databaseName here...)
    done
    
    # Outputs
    # RA
    # RB
    # R C
    # RD
    

    B. No whitespace in the names:

    listOfNames="RA
    RB
    R C
    RD"
    
    for databaseName in $listOfNames  # Note: No quotes
    do
      echo "$databaseName"  # (i.e. do action / processing of $databaseName here...)
    done
    
    # Outputs
    # RA
    # RB
    # R
    # C
    # RD
    

    Notes

    1. In the second example, using listOfNames="RA RB R C RD" has the same output.

    Other ways to bring in data include:

    • stdin (listed below),
    • variables,
    • an array (the accepted answer),
    • a file...

    Read from stdin

    # line delimited (each databaseName is stored on a line)
    while read databaseName
    do
      echo "$databaseName"  # i.e. do action / processing of $databaseName here...
    done # <<< or_another_input_method_here
    
    1. the bash IFS "field separator to line" [1] delimiter can be specified in the script to allow other whitespace (i.e. IFS='\n', or for MacOS IFS='\r')
    2. I like the accepted answer also :) -- I've include these snippets as other helpful ways that also answer the question.
    3. Including #!/bin/bash at the top of the script file indicates the execution environment.
    4. It took me months to figure out how to code this simply :)

    Other Sources (while read loop)

提交回复
热议问题