我想编写一个经过15个字符串循环的脚本(多是数组吗?)那可能吗? shell
就像是: 数组
for databaseName in listOfNames then # Do something end
该声明数组不适用于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
尝试这个。 它正在工做并通过测试。 ide
for k in "${array[@]}" do echo $k done # For accessing with the echo command: echo ${array[0]}, ${array[1]}
本着与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
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
IFS='\\n'
或MacOS IFS='\\r'
) #!/bin/bash
表示执行环境。 其余来源( 读取循环时 ) 字符串
您能够使用${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=1; i<${arraylength}+1; i++ )); do echo $i " / " ${arraylength} " : " ${array[$i-1]} done
输出:
1 / 3 : one 2 / 3 : two 3 / 3 : three