捕獲 bash 函數的結果並允許其退出

捕獲 bash 函數的結果並允許其退出

該函數應該退出呼叫腳本:

crash() {
  echo error
  exit 1
}

這按預期工作:

echo before
crash
echo after         # execution never reaches here

但這並不:

echo before
x=$(crash)         # nothing is printed, and execution continues
echo after         # this is printed

如何捕獲函數的結果並允許其退出?

答案1

這是因為在子 shell 中$(crash)執行crash,因此exit適用於子 shell 而不是您的腳本。

如果由於腳本無論如何都退出而不會使用它,那麼在變數中捕獲輸出有什麼意義呢?

答案2

這應該可以解決您的問題:

echo before
x=$(crash) || exit       # if crash give -gt 0 value then exit with the same value
echo after

相關內容