Shell
sh AND 和 OR 在一個命令中
試圖在一行程式碼中檢查 3 個條件,但我被卡住了。
本質上,我需要編寫以下程式碼:
如果
string1 不等於 string2
和
string3 不等於 string4
或者
bool1 = 真
然後
顯示“滿足條件 - 執行程式碼…”。
根據評論中的要求,我更新了我的範例以嘗試使問題更清晰。
#!/bin/sh string1="a" string2="b" string3="c" string4="d" bool1=true # the easy-to-read way .... if [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] ; then echo "conditions met - running code ..." fi if $bool1 ; then echo "conditions met - running code ..." fi # or the shorter way ... [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] && echo "conditions met - running code ..." $bool1 && echo "conditions met - running code ..."
上面的程式碼可能會執行兩次:如果滿足前兩個條件,然後如果滿足第三個條件,則再次執行。這不是我需要的。
這個例子的問題在於它涉及到 2 個不同的“echo”呼叫——(注意:在實際程式碼中,它不是一個 echo,但你明白了)。我試圖通過將 3 個條件檢查組合到一個命令中來減少程式碼重複。
我敢肯定現在有幾個人在搖頭,對著螢幕大喊“這不是你做的!”
可能還有其他人在等待將其標記為重複…好吧,我看了,但如果我能從我讀過的答案中弄清楚如何做到這一點,我該死的。
有人可以啟發我嗎?:)
這將起作用:
if [ "$string1" != "$string2" ] \ && [ "$string3" != "$string4" ] \ || [ "$bool1" = true ]; then echo "conditions met - running code ..."; fi;
或環繞以
{ ;}
提高可讀性和便於將來維護。if { [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] ;} \ || [ "$bool1" = true ] ; then echo "conditions met - running code ..."; fi;
注意事項:
- 沒有布爾變數這樣的東西。.
- 大括號需要最後的分號 (
{ somecmd;}
)。&&
並在上面從左到右||
評估-優先級高於僅在內部和&&``||
(( ))``[[..]]
&&
更高的優先級只發生在[[ ]]
證明如下。假設bool1=true
。與
[[ ]]
:bool1=true if [[ "$bool1" == true || "$bool1" == true && "$bool1" != true ]]; then echo 7; fi #1 # Print 7, due to && higher precedence than || if [[ "$bool1" == true ]] || { [[ "$bool1" == true && "$bool1" != true ]] ;}; then echo 7; fi # Same as #1 if { [[ "$bool1" == true || "$bool1" == true ]] ;} && [[ "$bool1" != true ]] ; then echo 7; fi # NOT same as #1 if [[ "$bool1" != true && "$bool1" == true || "$bool1" == true ]]; then echo 7; fi # Same result as #1, proved that #1 not caused by right-to-left factor, or else will not print 7 here
與
[ ]
:bool1=true if [ "$bool1" == true ] || [ "$bool1" == true ] && [ "$bool1" != true ]; then echo 7; fi #1, no output, due to && IS NOT higher precedence than || if [ "$bool1" == true ] || { [ "$bool1" == true ] && [ "$bool1" != true ] ;}; then echo 7; fi # NOT same as #1 if { [ "$bool1" == true ] || [ "$bool1" == true ] ;} && [ "$bool1" != true ]; then echo 7; fi # Same as #1 if [ "$bool1" != true ] && [ "$bool1" == true ] || [ "$bool1" == true ]; then echo 7; fi # Proved that #1 not caused by || higher precedence than &&, or else will not print 7 here, instead #1 is only left-to-right evaluation