簡體   English   中英

Bash while循環在處理多個測試條件時的行為不同

[英]Bash while loop behaves differently dealing with multiple test conditions

我想知道是否有人可以解釋為什么while循環將多次測試條件與if循環區別對待。 我已經驗證了2個測試,分別為對與錯:

Bash$ test ! -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)"; echo $?
0
Bash$ test ! -e "unsentData.tmp"; echo $?
1
Bash$ 

當我將這2個測試與AND到if語句中時,按預期方式我得到了False的集合:

Bash$ if [ ! -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)" ] && [ ! -e "unsentData.tmp" ]; then echo "True"; else echo "False"; fi
False
Bash$

現在,當我將2個測試放入一個while循環中時,我希望在滿足兩個條件之前都可以入睡,但我立即獲得了真實的結果。

Bash$ while [ ! -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)" ] && [ ! -e "unsentData.tmp" ]; do sleep 1; done; echo -e "All files Exist\n$(ls /opt/pcf/mfe/unsentXmlToTSM/xmlConnection0_TSM/)"
All files Exist 
unsentData.tmp
Bash$

我在這里想念什么? 我只想寫一些東西,等到兩個條件都滿足后再退出循環

一種

我認為您的假設很陳舊。 While確實在dodone之間執行代碼,而條件成立。 如if語句的輸出所示,您的條件總和為false。 因此,while循環的主體永遠不會執行。 嘗試:

while ! ( [ ! -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)" ] && 
          [ ! -e "unsentData.tmp" ] )  
do 
    sleep 1
done 
echo -e "All files Exist\n$(ls /opt/pcf/mfe/unsentXmlToTSM/xmlConnection0_TSM/)"
while [ ! -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)" ] && [ ! -e "unsentData.tmp" ]
    do sleep 1
done

==>

while false
    do sleep 1
done

所以do sleep 1根本沒有運行。

只要(“ while ”)條件成立,就執行while循環; 聽起來您想運行循環直到其條件為真。 bash有一個until做到的循環:

until [ ! -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)" ] && [ ! -e "unsentData.tmp" ]; do
    sleep 1
done
echo -e "All files Exist\n$(ls /opt/pcf/mfe/unsentXmlToTSM/xmlConnection0_TSM/)"

或者,您可以否定條件(例如,使用“在剩余文件時,執行...”,而不是“直到所有文件都完成,執行...”)。 在這種情況下,僅僅表示去除的各個條件否定和切換以及一種

while [ -n "$(find . -maxdepth 1 -name '*.xml' -print -quit)" ] || [ -e "unsentData.tmp" ]; do
    sleep 1
done
echo -e "All files Exist\n$(ls /opt/pcf/mfe/unsentXmlToTSM/xmlConnection0_TSM/)"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM