3

I am working on a shell script, and want to handle various exit codes that I might come across. To try things out, I am using this script:

#!/bin/sh
echo "Starting"
trap "echo \"first one\"; echo \"second one\"; " 1
exit 1;

I suppose I am missing something, but it seems I can't trap my own "exit 1". If I try to trap 0 everything works out:

#!/bin/sh
echo "Starting"
trap "echo \"first one\"; echo \"second one\"; " 0
exit

Is there anything I should know about trapping HUP (1) exit code?

Jolta
  • 2,620
  • 1
  • 29
  • 42
jpou
  • 1,935
  • 2
  • 21
  • 30

3 Answers3

5

trap dispatches on signals the process receives (e.g., from a kill), not on exit codes, with trap ... 0 being reserved for process ending. trap /blah/blah 0 will dispatch on either exit 0 or exit 1

Charles Stewart
  • 11,661
  • 4
  • 46
  • 85
2

That's just an exit code, it doesn't mean HUP. So your trap ... 1 is looking for HUP, but the exit is just an exit.

In addition to the system signals which you can list by doing trap -l, you can use some special Bash sigspecs: ERR, EXIT, RETURN and DEBUG. In all cases, you should use the name of the signal rather than the number for readability.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
0

You can also use || operator, with a || b, b gets executed when a failed

#!/bin/sh

failed
{
    echo "Failed $*"
    exit 1
}

dosomething arg1 || failed "some comments"
fa.
  • 2,456
  • 16
  • 17