我想編寫一個經過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