在Bash中循环遍历字符串数组?

我想编写一个经过15个字符串循环的脚本(多是数组吗?)那可能吗? shell

就像是: 数组

for databaseName in listOfNames
then
  # Do something
end

#1楼

该声明数组不适用于Korn shell。 将如下示例用于Korn shell: bash

promote_sla_chk_lst="cdi xlob"

set -A promote_arry $promote_sla_chk_lst

for i in ${promote_arry[*]};
    do
            echo $i
    done

#2楼

尝试这个。 它正在工做并通过测试。 ide

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

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

#3楼

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

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.名称中不能有空格: 测试

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

笔记 spa

  1. 在第二个示例中,使用listOfNames="RA RB RC RD"具备相同的输出。

引入数据的其余方式包括: code

从stdin读取 three

# 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. 能够在脚本中指定bash IFS “行分隔符” [ 1 ]分隔符,以容许其余空格(即IFS='\\n'或MacOS IFS='\\r'
  2. 我也喜欢接受的答案:)-我将这些摘要做为其余有用的方式也能够回答问题。
  3. 脚本文件顶部包含#!/bin/bash表示执行环境。
  4. 我花了几个月的时间弄清楚如何简单地编写此代码:)

其余来源( 读取循环时字符串


#4楼

您能够使用${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

#5楼

这些答案都没有包含计数器...

#!/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=1; i<${arraylength}+1; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i-1]}
done

输出:

1  /  3  :  one
2  /  3  :  two
3  /  3  :  three
相关文章
相关标签/搜索