[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Help-bash] Find out trap ERR from within a function when errtrace is un
From: |
Patrick Schleizer |
Subject: |
[Help-bash] Find out trap ERR from within a function when errtrace is unset? |
Date: |
Wed, 25 Feb 2015 15:31:41 +0000 |
Hi!
TLDR:
If errtrace is not in use, and one is within a function, is it possible
from within the function to find out which trap ERR is set on global level?
(This is related to my previous thread "run at global level from a
function".)
Long:
I know there are some issues with reusability [1] of bash shell
functions, but I wanted to see how far I come. Works okay for now for me
except for a small glitch I am asking about here.
Here is the pseudo code for the main script:
----------
#!/bin/bash
trap 'echo "trap ERR 1 of main script" ERR'
## do some stuff
source /path/to/some-bash-lib
## do some other stuff
trap 'echo "trap ERR 2 of main script" ERR'
## do some other stuff
function_provided_by_some_bash_lib
## function_provided_by_some_bash_lib runs an init function,
## that sets up shell options (dotglob etc.) as required and a deinit
function that undo it if necessary
## (if not already previously set by the main script.)
## The idea is for function_provided_by_some_bash_lib to have its own
trap ERR while it's running and to restore the trap of main script in
the deinit function.
----------
The idea is to use separate trap ERR in /path/to/some-bash-lib than in
the main script. So /path/to/some-bash-lib should not mess up traps in
the main script.
The following example works, even though "set -o errtrace" is not set,
the existing trap can be set, because it is set outside a function, on
global level.
----------
#!/bin/bash
trap "echo traptest" ERR
trap_extract() {
## Thanks to Richard Hansen - http://stackoverflow.com/a/7287873/2605155
printf '%s\n' "$3"
}
existing_trap="$(eval "trap_extract $(trap -p ERR)")"
----------
The next example doesn't work, because "set -o errtrace" is not set.
Therefore the function trap_store_existing did not inherit the trap,
hence "trap -p ERR" cannot detect it.
----------
#!/bin/bash
trap "echo traptest" ERR
trap_extract() {
## Thanks to Richard Hansen - http://stackoverflow.com/a/7287873/2605155
printf '%s\n' "$3"
}
trap_store_existing() {
existing_trap="$(eval "trap_extract $(trap -p ERR)")"
}
trap_store_existing
----------
Cheers,
Patrick
[1] http://mywiki.wooledge.org/BashWeaknesses
- [Help-bash] Find out trap ERR from within a function when errtrace is unset?,
Patrick Schleizer <=