Does bash have a hook that is run before executing a command

bashcommand linehook

In bash, can I arrange for a function to be executed just before running a command?

There is $PROMPT_COMMAND, which is executed before showing a prompt, i.e., just after running a command.

Bash's $PROMPT_COMMAND is analogous to zsh's precmd function; so what I'm looking for is a bash equivalent to zsh's preexec.

Example applications: set your terminal title to the command being executed; automatically add time before every command.

Best Answer

Not natively, but it can be hacked up using the DEBUG trap. This code sets up preexec and precmd functions similar to zsh. The command line is passed as a single argument to preexec.

Here is a simplified version of the code to set up a precmd function that is executed before running each command.

preexec () { :; }
preexec_invoke_exec () {
    [ -n "$COMP_LINE" ] && return  # do nothing if completing
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # don't cause a preexec for $PROMPT_COMMAND
    local this_command=`HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//"`;
    preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG

This trick is due to Glyph Lefkowitz; thanks to bcat for locating the original author.

Edit. An updated version of Glyph's hack can be found here: https://github.com/rcaloras/bash-preexec

Related Question