5

I can get a function myHandler() to execute before a bash command by doing the following:

function myHandler() {
   ...
}
trap 'myHandler' DEBUG

However, I'd like to be able to proceed with or abort the execution of the impending BASH_COMMAND based on a runtime condition within myHandler as follows:

function myHandler() {
   if ! myCondition ; then
      abort the execution of BASH_COMMAND right here
   fi
   # Proceed with the execution of BASH_COMMAND
}

Is this possible?

4

You can, just enable extdebug and return a non-zero code (See the description of extdebug option) from myHandler:

$ function myHandler() {
  if [[ $SKIP = "true" ]]; then return 1; fi;
  echo 'myHandler execute'
}
$ trap 'myHandler' DEBUG
$ shopt -s extdebug
$ echo 1
myHandler execute
1
$ SKIP=true
myHandler execute
$ echo 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.