Distributing exit code for the shell that invokes an error trap in case of an error

Is it possible to distribute the exit code to the caller in the event of a syntax error in a Bash script with an EXIT trap? For example, if I have:

#! /bin/bash

set -eu

trap "echo dying!!" EXIT

echo yeah
echo $UNBOUND_VARIABLE
echo boo

Then, by running it, you will get exit code 0, even if the script did not complete successfully:

$ bash test.sh
yeah
test.sh: line 8: UNBOUND_VARIABLE: unbound variable
dying!!

$ echo $?
0

But if I comment on the output trap, the script returns 1. Alternatively, if I replace the string with an unbound variable with a command that returns a non-zero value (for example /bin/false), this output value propagates as I would like it to.

+4
source share
2 answers

Bash. script Bash 4.2, 3.2. , , script Bash:

#!/bin/bash

$BASH sub.sh
RETVAL=$?

if [[ "$RETVAL" != "0" ]]; then
  echo "Dying!! Exit code: $RETVAL"
fi

sub.sh:

set -eu

echo yeah
echo $UNBOUND_VARIABLE
echo boo
+1

. trap, echo, .

, exit .

#!/bin/bash

set -eu

die() {
  echo "Dying!!"
  exit "$1"
}

trap 'die $?' EXIT

echo yeah
echo $unbound
echo boo

, set -e - , script , , .

+6

All Articles