我有一個腳本,檢查以下函數的返回狀態:如何測試中的Bash命令的非零退出狀態?
function is_git_repository {
git branch &> /dev/null
}
如果你在一個混帳回購協議是它返回0
,並且128
如果你不是。
我沒有問題,測試,看看如果返回值是0
;如預期了以下工作:
if is_git_repository ; then
echo you are in a git repo
else
echo you are NOT in a git repo
fi
但它是當我試圖測試那些是什麼,除了0
當我遇到問題的退出狀態。我試過以下,但他們沒有工作:
if [[ "$(is_git_repository)" != "0" ]] ; ...
結果始終爲true(link)if [[ "$(is_git_repository)" -ne "0" ]] ; ...
始終得到falseif [[ "$(is_git_repository)" != 0 ]] ; ...
結果始終爲trueif [[ "$(is_git_repository)" -ne 0 ]] ; ...
始終計算爲假if [[ ! "$(is_git_repository)" ]] ; ...
始終評估爲真if !is_git_repository ; ...
只是回聲c ommand回到我,但沒有爆炸(wtf?)
在if語句中檢查命令的非零退出狀態的正確方法是什麼?
你似乎在尋找$? – devnull
「源」您鏈接到既不接受,也不是最高的投票答案的問題。 –