在 Bash 中檢查退出程式碼

Muhammad Husnain 2022年6月15日
在 Bash 中檢查退出程式碼

本教程將介紹幾種在 Bash 中獲取和顯示語句退出狀態的方法。我們將首先討論使用簡單的 if 語句來獲取退出狀態,然後我們將討論用於獲取退出狀態的替代方法和簡寫符號。

檢查 Bash 中的退出程式碼

退出狀態本質上是一個整數,告訴我們命令是否成功。不直觀地,退出狀態 0 表示成功,任何非零值表示失敗/錯誤。

這種非直觀的解決方案允許不同的錯誤程式碼表示不同的錯誤。例如,如果沒有找到命令,則返回 127 的退出狀態。

在 Bash 中檢查退出程式碼的方法是使用 $? 命令。如果你希望輸出退出狀態,可以通過以下方式完成:

# your command here
testVal=$?
echo testVal

我們知道非零退出程式碼用於報告錯誤。如果我們想檢查一般的錯誤,我們可以編寫一個小指令碼,其中包含有問題的命令和一個 if 語句來檢查退出程式碼是否存在錯誤(非零)或退出程式碼是否指示正確執行.

# your command here
testVal=$?
if [$testVal -ne 0]; then
    echo "There was some error"
fi
exit $testVal

可以使用 $? 上的 test 來完成速記符號命令。此程式碼的最小示例可以是:

# your command here
test $? -eq 0 || echo "There was some error"

為了更好地理解上述陳述,我們可以對其進行擴充套件。

# your command here
exitStat = $?
test $exitStat -eq 0 && echo "No error! Worked fine" || echo "There was some error";
exit $exitStat

在上面,我們可以看到成功執行時的 "No error! Worked fine" 訊息,以及失敗時的錯誤訊息。

重要說明和可能的替代解決方案

如果使用退出程式碼來檢視命令是否正確執行,我們有一個更簡單的選擇。

# define your_command here
# your_command = enter a command here
if your_command; then
    echo command returned true
else
    echo command returned an error
fi

在這種情況下,我們通常會得到與使用前幾個選項相同的輸出。此外,獲取有關退出程式碼的特定資訊或獲取特定退出程式碼需要手動執行 $?

Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

LinkedIn