Arrays 在Bash中循环字符串数组?

Arrays 在Bash中循环字符串数组?,arrays,bash,shell,Arrays,Bash,Shell,我想写一个循环15个字符串的脚本(可能是数组?) 比如: for databaseName in listOfNames then # Do something end 当然,这是可能的 for databaseName in a b c d e f; do # do something like: echo $databaseName done 有关详细信息,请参阅。您可以这样使用它: ## declare an array variable declare -a arr=("e

我想写一个循环15个字符串的脚本(可能是数组?)

比如:

for databaseName in listOfNames
then
  # Do something
end

当然,这是可能的

for databaseName in a b c d e f; do
  # do something like: echo $databaseName
done 

有关详细信息,请参阅。

您可以这样使用它:

## 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
也适用于多行数组声明

declare -a arr=("element1" 
                "element2" "element3"
                "element4"
                )

声明数组不适用于Korn shell。对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

试试这个。它正在工作并经过测试

for k in "${array[@]}"
do
    echo $k
done

# For accessing with the echo command: echo ${array[0]}, ${array[1]}

本着与4ndrew的回答相同的精神:

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
注释

for Item in Item1 Item2 Item3 Item4 ;
  do
    echo $Item
  done
for Item in Item1 \
            Item2 \
            Item3 \
            Item4
  do
    echo $Item
  done
  • 在第二个示例中,使用
    listOfNames=“RA RB R C RD”
    具有相同的输出
  • 引入数据的其他方式包括:

    • 标准DIN(如下所列)
    • ,
    • (被接受的答案)
    从标准文本中读取

    #行分隔(每个数据库名存储在一行中)
    读取数据库名时
    做
    echo“$databaseName”#即在此处执行$databaseName的操作/处理。。。
    
    完成#您可以使用
    ${arrayName[@]}

    #!/bin/bash
    # declare an array called files, that contains 3 values
    files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
    for i in "${files[@]}"
    do
        echo "$i"
    done
    

    这些答案中没有一个包含计数器

    #!/bin/bash
    ## declare an array variable
    declare -a array=("one" "two" "three")
    
    # get length of an array
    arraylength=${#array[@]}
    
    # use for loop to read all values and indexes
    for (( i=0; i<${arraylength}; i++ ));
    do
      echo "index: $i, value: ${array[$i]}"
    done
    

    如果您使用的是Korn shell,则有“设置-A databaseName”,否则有“声明-A databaseName

    要在所有shell上编写脚本

     set -A databaseName=("db1" "db2" ....) ||
            declare -a databaseName=("db1" "db2" ....)
    # now loop 
    for dbname in "${arr[@]}"
    do
       echo "$dbname"  # or whatever
    
    done
    

    它应该适用于所有外壳。

    这也很容易阅读:

    FilePath=(
        "/tmp/path1/"    #FilePath[0]
        "/tmp/path2/"    #FilePath[1]
    )
    
    #Loop
    for Path in "${FilePath[@]}"
    do
        echo "$Path"
    done
    

    每个Bash脚本/会话的可能第一行:

    say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }
    
    使用例如:

    $ aa=( 7 -4 -e ) ; say "${aa[@]}"
    7
    -4
    -e
    
    可以考虑:
    echo
    -e
    解释为此处的选项

    listOfNames="db_one db_two db_three"
    for databaseName in $listOfNames
    do
      echo $databaseName
    done
    
    或者只是

    for databaseName in db_one db_two db_three
    do
      echo $databaseName
    done
    

    这与user2533809的回答类似,但每个文件都将作为单独的命令执行

    #!/bin/bash
    names="RA
    RB
    R C
    RD"
    
    while read -r line; do
        echo line: "$line"
    done <<< "$names"
    
    #/bin/bash
    names=“RA
    铷
    R C
    RD“
    而read-r行;做
    回音行:“$line”
    
    完成我循环浏览我的项目数组,以进行
    git pull
    更新:

    #!/bin/sh
    projects="
    web
    ios
    android
    "
    for project in $projects do
        cd  $HOME/develop/$project && git pull
    end
    
    单线循环

     declare -a listOfNames=('db_a' 'db_b' 'db_c')
     for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
    
    您将得到这样的输出

    db_a
    db_b
    db_c
    

    for Item in Item1 Item2 Item3 Item4 ;
      do
        echo $Item
      done
    
    for Item in Item1 \
                Item2 \
                Item3 \
                Item4
      do
        echo $Item
      done
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    保留空间;单引号或双引号列表条目和双引号列表扩展。

    for Item in 'Item 1' 'Item 2' 'Item 3' 'Item 4' ;
      do
        echo "$Item"
      done
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    多行列表

    for Item in Item1 Item2 Item3 Item4 ;
      do
        echo $Item
      done
    
    for Item in Item1 \
                Item2 \
                Item3 \
                Item4
      do
        echo $Item
      done
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    

    简单列表变量
    List=( Item1 Item2 Item3 )
    

    显示列表变量:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    循环浏览列表:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    创建一个函数来浏览列表:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    使用declare关键字(命令)创建列表,技术上称为数组:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    创建关联数组。字典:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    列表中的CSV变量或文件
    将内部字段分隔符从空格更改为所需的内容
    在下面的示例中,它被更改为逗号

    List="Item 1,Item 2,Item 3"
    Backup_of_internal_field_separator=$IFS
    IFS=,
    for item in $List; 
      do
        echo $item
      done
    IFS=$Backup_of_internal_field_separator
    
    输出:

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    如果需要编号:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    这被称为回勾。将命令放在back ticks中

    `command` 
    
    它位于键盘上的数字1旁边,或位于标准美式英语键盘上的tab键上方

    List=()
    Start_count=0
    Step_count=0.1
    Stop_count=1
    for Item in `seq $Start_count $Step_count $Stop_count`
        do 
           List+=(Item_$Item)
        done
    for Item in ${List[*]}
        do 
            echo $Item
        done
    
    输出为:

    Item_0.0
    Item_0.1
    Item_0.2
    Item_0.3
    Item_0.4
    Item_0.5
    Item_0.6
    Item_0.7
    Item_0.8
    Item_0.9
    Item_1.0
    
    更加熟悉bash行为:

    echo ${List[*]}
    
    for Item in ${List[*]} 
      do
        echo $Item 
      done
    
    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    
    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    
    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    
    ` 
    
    在文件中创建列表

    cat <<EOF> List_entries.txt
    Item1
    Item 2 
    'Item 3'
    "Item 4"
    Item 7 : *
    "Item 6 : * "
    "Item 6 : *"
    Item 8 : $PWD
    'Item 8 : $PWD'
    "Item 9 : $PWD"
    EOF
    

    脚本或函数的隐式数组: 除了的正确答案:如果循环的基本语法为:

    for var in "${arr[@]}" ;do ...$var... ;done
    
    有一种特殊情况:

    运行脚本或函数时,在命令行传递的参数将被分配给数组变量
    $@
    ,您可以通过
    $1
    $2
    $3
    等方式访问

    可通过以下方式填充(用于测试)

    上的循环数组可以简单地写入:

    for item ;do
        echo "This is item: $item."
      done
    
    注意中的保留工作
    不存在,也没有数组名称

    样本:

    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: ....
    
    请注意,这与

    for item in "$@";do
        echo "This is item: $item."
      done
    
    然后转换成脚本: 将其保存在脚本
    myscript.sh
    chmod+x myscript.sh
    ,然后

    ./myscript.sh arg1 arg2 arg3 ...
    Doing something with 'arg1'.
    Doing something with 'arg2'.
    Doing something with 'arg3'.
    Doing something with '...'.
    
    在函数中相同:
    令人惊讶的是,现在还没有人发布这篇文章——如果在数组中循环时需要元素的索引,可以这样做:

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

    index: 0, value: one
    index: 1, value: two
    index: 2, value: three
    
    Item1
    Item2
    Item3
    Item4
    
    Item 1
    Item 2
    Item 3
    Item 4
    
    Item1
    Item2
    Item3
    Item4
    
    Item1 Item2 Item3
    
    Item1
    Item2
    Item3
    
    element 1
    element 2
    element 3
    
     Argentina is in America
     Vietnam is in Asia
     France is in Europe
    
    Item 1
    Item 2
    Item 3
    
    0foo
    1巴
    2巴兹
    
    我发现这比“传统”for循环样式(
    for((I=0;I简单方式)优雅得多:

    arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array
    
    len=${#arr[*]}  # it returns the array length
    
    #iterate with while loop
    i=0
    while [ $i -lt $len ]
    do
        echo ${arr[$i]}
        i=$((i+1))
    done
    
    
    #iterate with for loop
    for i in $arr
    do
      echo $i
    done
    
    #iterate with splice
     echo ${arr[@]:0:3}
    

    我真正需要的是这样的东西:

    ## 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
    
    表示$(_数组)中的i;做某事;完成
    
    例如:

    对于$中的i(ps-aux | grep vlc | awk'{print$2}');do kill-9$i;完成
    

    (将终止名称中包含vlc的所有进程)

    如何循环数组取决于新行字符的存在。新行字符分隔数组元素时,数组可以称为
    “$array”
    ,否则应称为
    “${array[@]}”
    。下面的脚本将说明这一点:

    #!/bin/bash
    
    mkdir temp
    mkdir temp/aaa
    mkdir temp/bbb
    mkdir temp/ccc
    array=$(ls temp)
    array1=(aaa bbb ccc)
    array2=$(echo -e "aaa\nbbb\nccc")
    
    echo '$array'
    echo "$array"
    echo
    for dirname in "$array"; do
        echo "$dirname"
    done
    echo
    for dirname in "${array[@]}"; do
        echo "$dirname"
    done
    echo
    echo '$array1'
    echo "$array1"
    echo
    for dirname in "$array1"; do
        echo "$dirname"
    done
    echo
    for dirname in "${array1[@]}"; do
        echo "$dirname"
    done
    echo
    echo '$array2'
    echo "$array2"
    echo
    for dirname in "$array2"; do
        echo "$dirname"
    done
    echo
    for dirname in "${array2[@]}"; do
        echo "$dirname"
    done
    rmdir temp/aaa
    rmdir temp/bbb
    rmdir temp/ccc
    rmdir temp
    

    这种方法的问题是什么?在简单的情况下,它似乎是有效的,而且比@anubhava的答案更直观。这在命令替换方面尤其有效,例如,$年的
    (seq 2000 2013)
    。问题是,他询问了对数组的迭代。如果必须在多个位置对同一数组进行迭代,“declare”方法效果最好。这种方法更简洁,但灵活性较差。为什么这不是#1?它更简洁,只需设置一个字符串即可轻松重用数组,即
    DATABASES=“a b c d e f”
    。尝试编辑器中的代码高亮显示,使您的代码看起来不错。很高兴知道,但这个问题是关于bash.Lotsa错误的。不能有带空格的列表项,不能有带全局字符的列表项。
    对于${foo[*]}中的i
    基本上总是错误的--
    对于“${foo[@]}”中的i
    是一种保留原始列表边界并防止全局扩展的表单。而echo需要是
    echo“$i”
    这会给人留下这样的印象,即eol被用作字符串分隔符,因此字符串中允许有空格。但是,字符串