help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] access exit code from within exit trap handler?


From: Greg Wooledge
Subject: Re: [Help-bash] access exit code from within exit trap handler?
Date: Tue, 14 Apr 2015 08:21:05 -0400
User-agent: Mutt/1.4.2.3i

On Tue, Apr 14, 2015 at 11:19:09AM +0000, Patrick Schleizer wrote:
> exit_handler() {
>    ## Is there a way figure out what exit code caused execution of this
> handler?
>    true "exit code: "
>    ## ...
> }

The code you're looking for is: echo $?
But obviously you'll have to save $? before you call true.

imadev:~$ cat foo
#!/bin/bash
trap 'echo "exit $?"' EXIT
exit 42

imadev:~$ ./foo
exit 42

Exit codes do not "cause execution of [a] handler".  An exit code is the
content of a special parameter.  That parameter is available for your use.
What causes the execution of the EXIT trap is the exit command (or
reaching the end of file).  The exit command may, or may not, change the
value of the $? special parameter, depending on whether it was given an
argument.

Here's an example of an exit command that does not change the value of $?:

imadev:~$ cat foo
#!/bin/bash
trap 'echo "exit $?"' EXIT
cd /nonexistent || exit

imadev:~$ ./foo
./foo: line 3: cd: /nonexistent: No such file or directory
exit 1



reply via email to

[Prev in Thread] Current Thread [Next in Thread]