簡體   English   中英

盡管設置了“ -e”,但如何“捕獲”非零退出代碼,然后回顯錯誤代碼

[英]How to “catch” non-zero exit-code despite “set -e” then echo error code

我有劇本

#!/bin/bash

set -e

if [[ ! $(asd) ]]; then
   echo "caught command failure with exit code ${?}"
fi

echo "end of script" 

腳本的目的是使用set -e終止在任何非零命令退出代碼上的執行,除非命令被“捕獲”(來自Java)(如出現錯誤的命令asd

if [[ ! $(asd) ]]; then
   echo "caught command failure with exit code ${?}"
fi

但是,盡管我“捕獲”了錯誤並且end of script打印到了終端,但錯誤代碼為0

echo "caught command failure with exit code ${?}"

所以我的問題是我如何才能“捕獲”一個錯誤的命令,並同時打印該命令的exit code

編輯

我重構了腳本,結果相同,退出代碼仍為0

#!/bin/bash

set -e

if ! asd ; then
   echo "caught command failure with exit code ${?}"
fi

echo "end of script"

只需使用短路:

asd || echo "asd exited with $?" >&2

如何“捕獲”錯誤的命令,並打印該命令的退出代碼?

我經常這樣做:

asd && ret=$? || ret=$? 
echo asd exited with $ret

整個表達式的退出狀態為0 ,因此set -e不會退出。 如果asd成功,則第一個ret=$? $?執行$? 設置為0 ,如果失敗,則第一個ret=$? 省略,第二個執行。

有時我這樣做:

ret=0
asd || ret=$?
echo asd exited with $ret

它的工作原理相同,我忘記了&&|| 應該先走。 您也可以這樣做:

if asd; then
   ret=0
else
   ret=$?
fi
echo asd exited with $ret

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM