
我寫了下面這段 bash 腳本。
if [ $(tmux has -t junk) ]
then
echo zero
else
echo one
fi
無論會話是否存在,它總是會傳回 1。我透過執行 tmux 語句然後執行 $$? 來檢查命令列。 。它的行為符合預期,如果會話存在則為零,如果會話不存在則為 1 為什麼不是 if 語句的行為方式不同。我嘗試更改 if 語句,如下所示
tmux has -t junk
if [ $? -eq 0 ]
then
echo zero
else
echo one
fi
上面的事情有效。那麼第一個語句塊有什麼問題呢?
答案1
如前所述,if [ $(tmux has -t junk) ]
expand to 的if [ ]
值為 false。
你可以使用:
if tmux has -t junk; then
echo OK
else
echo ERR
fi
或者如果你想要更短的:
tmux has -t junk || echo ERR
或者
tmux has -t junk && echo OK || echo ERR
如果更合適,您也可以否定它,如下所示:
! tmux has -t junk || echo OK
! tmux has -t junk && echo ERR || echo OK
etc.
編輯:
另外,如果命令產生輸出,您可能希望將該輸出重定向到黑洞,如下/dev/null
所示:
if my_cmd >/dev/null; then echo OK else; echo ERR; fi
如果該命令產生文字錯誤,您可能還想透過以下方式重定向標準錯誤:
if my_cmd >/dev/null 2>&1; then echo OK else; echo ERR; fi
接下來的內容,您可能已經很了解,但添加它是為了更加完整。
如前所述:$?
是取得程式傳回值的唯一方法。
有些程式的返回值不同,並且可能具有相當明確的含義。
所以例如:
mycmd
ecode=$?
case "$ecode" in
0) echo "Success";;
1) echo "Operation not permitted";;
2) echo "No such file or directory";;
esac
透過這一點,可以對特定錯誤採取適當的措施。
如果你安裝了MySQL,你可以這麼做錯誤:
for i in {0..50}; do perror $i; done
# And
for i in {1000..1050}; do perror $i; done
來感受一下。
答案2
當您使用:
if [ $(tmux has -t junk) ]
這會檢查命令的輸出tmux has -t junk
,但不檢查回傳值。
因此,由於它總是像第一種情況一樣列印一個,這意味著該tmux has -t junk
命令不會在標準輸出上列印任何內容。
所以在第一種情況下,
if [ $(tmux has -t junk) ]
被評價為
if [ ]