I'm looking for a solution that will automatically allow me to call a function with specific parameters in a certain situation.
Here is the specific scenario:
When an error occurs, I can set up my error handler like this:
function _trap_err () {
echo "An error occurred in "$1":"$2" on "$3":"$4".
}
And I can set the trap to collect the debugging data I need automatically – at the correct moment in execution.
trap '_trap_err "$BASH_SOURCE" "$BASH_LINENO" "$FUNCNAME" "$BASH_COMMAND" ' ERR
AFAIK, this only works when bash detects an error and emits the signal.
I'd like to extend this behavior so that I can manually signal an error when a check fails, for example, when checking function arguments:
# Usage: myfunc <requiredarg>
function myfunc () {
[[ $# != 1 ]] && emit_err_signal
}
If there is a way to manually emit that error signal, then its possible to automatically collect that debugging argument at the correct time in execution to provide meaningful debugging information.
The alternative is to simply display an error message – which has to be hardcoded in every check – and doesn't display where the error occurred.
Any ideas?
EDIT
I should have specified that I this is for my .bashrc files and I don't want them to quit, I just want debugging information. Traps may have be overkill for this, i think the following solution may work:
function _debug () {
local _message=${1:-""}
printf "\e[1;32m[BASHRC] DEBUG: %-20s - %s\e[0m\n" "$BASH_SOURCE:$BASH_LINENO" "$_message"
}
_debug "Testing debug message."
> [BASHRC] DEBUG: .bashrc.d/bashrc:18 - Testing debug message.
( ${unset?$(_function_call arg)} )
will kill only the subshell in which is called and still emit a message tostderr
. Please read this: unix.stackexchange.com/questions/81457/…