rcaloras / bash-preexec

⚡ preexec and precmd functions for Bash just like Zsh.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

It's possible to prevent the execution of the command?

diegobernardes opened this issue · comments

I'm looking for a way to use the preexec to do some validation and be able to prevent the actual command from being executed.
It's possible to do this?

Hey @diegobernardes, don't believe this is currently possible. While you could validate or do operations prior to the command being executed, not sure you could then stop its actual execution. One of the contributors more familiar with bash might have a suggestion though or a way cc @d630

According to this comment preexec respects the extdebug option, which causes "the next command [to be] skipped and not executed" if the DEBUG command returns a non-zero value.

So it should be possible as long as using extdebug is acceptable (but note this changes a number of behaviors of the shell, so you probably don't want to just enable it globally). Without extdebug I imagine this isn't possible, as @rcaloras said.

Looks like it works:

$ source bash-preexec.sh
$ preexec() { echo PREEXEC; return 1; }

# By default execution proceeds
$ echo CMD
PREEXEC
CMD

$ shopt -s extdebug
PREEXEC

# now echo is skipped
$ echo CMD
PREEXEC

# Fortunately(?) DEBUG doesn't fire on function (re)definitions
$ preexec() { echo PREEXEC; }

# Now execution can proceed
$ echo CMD
PREEXEC
CMD

@dimo414 thanks for chiming in! Forgot about this :)

So it should be possible as long as using extdebug is acceptable (but note this changes a number of behaviors of the shell, so you probably don't want to just enable it globally)

Want to underscore this point as my guess is this might make it not a viable solution for @diegobernardes. Closing this issue, feel free to reopen if needed!