[英]Bash script does not continue after for loop
我試圖用bash制作一個Mac Clippy。 這是我的一些代碼:
say "Hello there!"
declare -a assist_array=()
while true; do
if pgrep -xq -- "Mail"; then
assist_array+=('It looks like your trying to send an email. Would you like some help?')
fi
if pgrep -xq -- "Notes"; then
assist_array+=('It looks like your trying to take a note. Would you like some help?')
fi
arraylength=${#assist_array[@]}
for (( i=0; i<${arraylength}+1; i++ )); do
echo ${assist_array[i]}
say ${assist_array[i]}
assist_array=()
done
done
當我打開“郵件”時,它會回聲並說: "It looks like your trying to send an email. Would you like some help?"
然后換一行。 我同時打開了郵件和便箋。 我如何才能使其繼續掃描打開的應用程序而不會卡在for循環中?
您正在循環中清空數組。 結果,當嘗試下一次迭代時, ${assist_array[i]}
要打印的內容。 如果需要清空數組,請在循環結束后執行。
同樣,數組索引從0
到length-1
,而不是從1
到length
。 通常,您應該引用可能包含多個單詞的變量。
for (( i=0; i<${arraylength}; i++ )); do
echo "${assist_array[i]}"
say "${assist_array[i]}"
done
assist_array=()
我在您的代碼中看到兩個問題:
#!/bin/bash
while true; do
assist_array=() # reset the array
if pgrep -xq -- "Mail"; then
assist_array+=('It looks like your trying to send an email. Would you like some help?')
fi
if pgrep -xq -- "Notes"; then
assist_array+=('It looks like your trying to take a note. Would you like some help?')
fi
arraylength=${#assist_array[@]}
for ((i=0; i<arraylength; i++)); do
echo "${assist_array[i]}"
say "${assist_array[i]}"
done
# probably put a sleep here
done
say "Hello there!"
declare -a assist_array=()
while true; do
if pgrep -xq -- "Mail"; then
assist_array+=('It looks like your trying to send an email. Would you like some help?')
fi
if pgrep -xq -- "Notes"; then
assist_array+=('It looks like your trying to take a note. Would you like some help?')
fi
arraylength=${#assist_array[@]}
for (( i=0; i<${arraylength}; i++ )); do
echo ${assist_array[i]}
say ${assist_array[i]}
done
assist_array=()
done
上面的代碼應該為您工作。 問題在於數組是從零開始的,因此您對Assistant_array [2]的引用實際上是一個空字符串。 當您什么都不傳遞給“ say”時,它將顯示為stdin。
另外,正如其他答案所指出的(顯式或隱式),您正在初始化for循環內的數組。 您不應該這樣做,因為您還沒有讀完它。
因此,基本上,您只是堅持說等待標准輸入。 您可以按Ctrl-D結束當前程序上的標准輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.