I am trying to build a pre-exec checker in bash (using bash-preexec.sh)

In order to fail the command when the pre-exec hook fails, I need to run shopt -s extdebug (which fails the command when trap DEBUG command returns non-zero RC).

If I run shopt -s extdebug in my shell as a command, this works perfectly fine (the preexec checker just grepped for "OK" in a file containing word "FAIL", so command shouldn't execute):

> grep shopt .bashrc
> bash
bash-4.1$ echo TEST2
TEST2   <=== Expected, since I didn't turn on extdebug yet
bash-4.1$ shopt -s extdebug > /dev/null 2>&1
bash-4.1$ echo TEST2
bash-4.1$ # WHAT WAS EXPECTED. Command failed to execute.

However, when I add the command to my .bashrc, it has no effect:

> grep shopt .bashrc
shopt -s extdebug > /dev/null 2>&1
> bash
bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
bash: warning: cannot start debugger; debugging mode disabled
bash-4.1$ echo TEST2

What am I doing wrong, and how can I execute this in .bashrc (I need to execute it anytime the user logs in)?

  • Not sure if this belongs here or unix.SE. Please migrate if the latter. – DVK Jan 8 '18 at 23:31
  • Most likely your .bashrc is not used in your login shell. It is usually the case that you call it from .profile. – eckes Jan 9 '18 at 8:36
  • @eckes - sorry, that does not seem to be the case: (1) .bashrc is executed because the pre-exec hooks ARE getting installed successfullly (and they are in .bashrc). (2) I just moved the code from .bashrc to .profile and the behavior was 100% same as with .bashrc (the hooks work but the extdebug doesn't have any effect till I explicitly run it in the shell as a command) – DVK Jan 9 '18 at 14:40

OK, figured out the answer.

    set -o functrace > /dev/null 2>&1

is required (in addition to shopt -s extdebug) to have the functionality work in sub-shells. And somehow, .bashrc is treated as supershell of actual interactive shell, in a sense, if you don't add this, it won't take effect on interactive command prompt.

So, you need to add both command to .bashrc

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.