
Ich schreibe ein Shell-Skript. Dieses Shell-Skript wird in einer bash
Shell innerhalb eines Terminals ausgeführt. Es enthält eine zentrale Fehlerbehandlungsfunktion. Bitte sehen Sie sich das folgende grundlegende Demo-Snippet an:
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
Die Fehlerbehandlungsfunktion sollte das Skript beenden, aber NICHT das Terminal. Wie kann ich das erreichen?
Antwort1
Verwenden Sie bash
das integrierte , um beim Beenden des Skripts trap
eine Instanz zu erzeugen :bash
trap 'bash' EXIT
Aus 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.
Durch Ausführen wird also trap 'bash' EXIT
gelesen bash
und ausgeführt, wenn die Shell das Signal EXIT empfängt. Das Erzeugen einer interaktiven Shell hat folglich zur Folge, dass das Schließen des Terminals verhindert wird:
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