在錯誤處理函數中退出shell腳本而不退出終端

在錯誤處理函數中退出shell腳本而不退出終端

我正在寫一個shell腳本。該 shell 腳本bash在終端機內的 shell中執行。它包含一個中央錯誤處理函數。請參考以下基本示範片段:

function error_exit
{
   echo "Error: ${1:-"Unknown Error"}" 1>&2
   exit 1 # This unfortunately also exits the terminal
}

# lots of lines possibly calling error_exit
cd somewhere || error_exit "cd failed"
rm * || error_exit "rm failed"
# even more lines possibly calling error_exit

錯誤處理函數應該結束腳本,但不應該結束終端。我怎樣才能實現這個目標?

答案1

使用bash的內建指令在腳本退出時trap產生一個實例:bash

trap 'bash' EXIT

help trap

trap: trap [-lp] [[arg] signal_spec ...]
    Trap signals and other events.

    Defines and activates handlers to be run when the shell receives signals
    or other conditions.

    ARG is a command to be read and executed when the shell receives the
    signal(s) SIGNAL_SPEC.  If ARG is absent (and a single SIGNAL_SPEC
    is supplied) or `-', each specified signal is reset to its original
    value.  If ARG is the null string each SIGNAL_SPEC is ignored by the
    shell and by the commands it invokes.

    If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.

所以透過運行trap 'bash' EXITbash當shell收到EXIT訊號時,就會被讀取並執行;產生互動式 shell 將會產生阻止終端關閉的效果:

function error_exit
{
   echo "Error: ${1:-"Unknown Error"}" 1>&2
   exit 1 # This unfortunately also exits the terminal
}

trap 'bash' EXIT
# lots of lines possibly calling error_exit
cd somewhere || error_exit "cd failed"
rm * || error_exit "rm failed"
# even more lines possibly calling error_exit

相關內容