Sagi Sagi - 4 months ago 8x
Bash Question

Configure an action to execute on every user input

So far I've been only using aliases and functions defined at

file, but now I need to know how to configure a function to run before/after every command I make. How can I achieve it?


There is an environment variable PROMPT_COMMAND, see the manual


If set, the value is interpreted as a command to execute before the printing of each primary prompt ($PS1).

For a trivial case, set it like an alias:

PROMPT_COMMAND='echo "Something"'

For more complex stuff, you can have it call a function:

prompt_command () {
    # If username has underscore, shorten to 'a_b'; else just use first letter
    if [[ $USER == *?_?* ]]; then
        local suff="${USER##*_}"

I use this to modify the username in my prompt, so elsewhere in my .bashrc there is something like

export PS1="$un@\h \$"

The typical user@host $ prompt thus, but the username is dynamically shortened as specified in the PROMPT_COMMAND function.