Shell exit code

I am working on a shell script and want to handle various exit codes that I may have come across. To try, I use this script:

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

I suppose I'm missing something, but it seems like I can't catch the trap of my "exit 1". If I try to catch a trap, everything will work out:

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

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

+3
source share
3 answers

trapsends signals received by the process (for example, from kill), rather than exit codes, and the trap ... 0 is reserved to complete the process. trap /blah/blah 0will send to exit 0orexit 1

+5
source

, HUP. , trap ... 1 HUP, - .

, , trap -l, Bash sigspecs: ERR, EXIT, RETURN DEBUG. , .

+2

You can also use || operator with || b, b is executed on an unsuccessful error

#!/bin/sh

failed
{
    echo "Failed $*"
    exit 1
}

dosomething arg1 || failed "some comments"
0
source

Source: https://habr.com/ru/post/1727741/


All Articles