ターミナルを終了せずにエラー処理関数でシェルスクリプトを終了する

ターミナルを終了せずにエラー処理関数でシェルスクリプトを終了する

シェル スクリプトを書いています。このシェル スクリプトは、bashターミナル内のシェルで実行されます。このスクリプトには、中心的なエラー ハンドラー関数が含まれています。次の基本的なデモ スニペットを参照してください。

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シェルがシグナル EXIT を受け取ったときに が読み込まれて実行されます。対話型シェルを生成すると、結果的にターミナルが閉じなくなる効果があります。

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

関連情報