Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active December 17, 2020 13:09
Show Gist options
  • Save coderofsalvation/8268365 to your computer and use it in GitHub Desktop.
Save coderofsalvation/8268365 to your computer and use it in GitHub Desktop.
simple event/exception handling for bash using 2 simple functions. Handy to keep your bash code compact, responsive and extendable. The advantage of this is that it prevents a lot of if/else code.
# simple event / exception handling in bash
#
# onFoo(){
# echo "onFoo() called width arg $1!"
# }
#
# onExit(){
# echo "onExit called!"
# }
#
# doBar(){ # shift; # echo "foo was called with $1 $2"
# }
#
# foo(){
# event FOO_OCCURED xyz
# }
#
# init_eventlistener
#
# on FOO_OCCURED onFoo
# on EXIT onExit
# on foo doBar
#
# foo 123 abc
#
# OUTPUT:
# foo was called with 123 abc
# onFoo() called width arg xyz!
declare -A LISTENERS
init_eventlistener(){
event(){
E=$1; shift; [[ "$E" == "DEBUG" ]] && E="${BASH_COMMAND// */}"
for listener in "${LISTENERS[$E]}"; do
[[ "${#listener}" == 0 ]] && continue;
eval "$listener $@ ${BASH_COMMAND}";
done
}
on(){
if ! test "${LISTENERS['$1']+isset}"; then LISTENERS["$1"]=""; fi
LISTENERS["$1"]+="$2 " # luckily functionnames never contain spaces
}
# redirect traps to events
for i in EXIT SIGINT SIGTERM DEBUG; do trap "event $i" $i; done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment