Sagi Sagi - 6 months ago 10
Bash Question

Configure an action to execute on every user input

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

.bashrc
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?

Answer

There is an environment variable PROMPT_COMMAND, see the manual

PROMPT_COMMAND

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
    un="${USER:0:1}"
    if [[ $USER == *?_?* ]]; then
        local suff="${USER##*_}"
        un+=_"${suff:0:1}"
    fi
}
PROMPT_COMMAND=prompt_command

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.