[英]Unix bash shell script - Iterating an array in a 'for' loop
我有以下測試腳本:
#!/bin/sh
testArray=(A,B,C,D,E)
currentValue=''
tempValue=x
for i in "${testArray[@]}"
do
currentValue=$i
echo "Processing " ${currentValue}
if [ ${currentValue}==A ]
then
tempValue="$i 123"
else
tempValue=$i
fi
echo "Current loop " ${tempValue}
echo `date`
done
當我測試它時,我得到的輸出是
Processing A,B,C,D,E
Current loop A,B,C,D,E 123
Mon Dec 2 20:33:26 GMT 2013
看來Bash中的“ for”循環的工作方式與我慣於期待以下輸出的方式有所不同(即,對於每個數組元素重復“ for”循環中的內容)
Processing A
Current loop A 123
Mon Dec 2 20:29:44 GMT 2013
Processing B
Current loop B
Mon Dec 2 20:29:45 GMT 2013
Processing C
Current loop C
Mon Dec 2 20:29:46 GMT 2013
Processing D
Current loop D
Mon Dec 2 20:29:47 GMT 2013
Processing E
Current loop E
Mon Dec 2 20:29:48 GMT 2013
基本上,我想實現的目標是編寫一個遍歷數組列表的腳本,並根據依賴於數組中當前項值的不同參數執行同一命令。 我寫了上面的腳本來嘗試了解for循環的工作原理,但是我沒有得到期望的輸出。
這條線
testArray=(A,B,C,D,E)
創建一個具有單個元素的數組,即字符串'A,B,C,D,E'。 數組元素由空格而不是逗號分隔。 采用
testArray=(A B C D E)
您還需要空格添加到您if
語句(和技術,你應該使用=
內[...]
而不是==
,以及報價參數擴展):
if [ "${currentValue}" = A ]
另一種方式
將循環更改為:
for i in `echo ${testArray} | tr "," " "`
根據chepner的建議將條件語句更改為:
if [ "${currentValue}" = A ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.