使用 Bourne shell 4.2,我試圖在 if 陳述句中使用兩個條件,其中之一是 grep:
file=/tmp/file
cat $file
this is an error i am looking for
if [ -e "$file" ] && [ $(grep -q 'error' $file) ]; then echo "true"; else echo "false"; fi
false
我希望在這里回傳“真”,因為這兩個條件都是真的。
但是,這有效:
grep_count=$(grep --count 'error' /tmp/file)
if [ -e "$file" ] && [ $grep_count -gt 0 ]; then echo "true"; else echo "false"; fi
true
最后:
test -e /tmp/file
echo $?
0
grep -q 'error' /tmp/file
echo $?
0
我錯過了什么?如何在 if 陳述句中使用 grep ?
uj5u.com熱心網友回復:
您在測驗括號內濫用了命令替換:
if [ -e "$file" ] && [ $(grep -q 'error' $file) ]; then echo "true"; else echo "false"; fi
應該寫:
if [ -e "$file" ] && ( grep -q 'error' $file ); then echo "true"; else echo "false"; fi
命令替換 $(command) 允許替換命令的輸出來代替命令名稱本身。因此,您所做的是測驗空字串的內容,例如:
[ "" ]
回傳'1',并使您的條件不滿意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440289.html
上一篇:ifelse函式基于多個條件
