Ubuntu – How to run a command before or after every command written in the console

bashcommand line

I want to run a command before and after every single command that gets executed in a terminal (i.e. clear before and then reset). I want this to happen automatically and not with a short alias or similar.

I have looked into bashrc and /usr/share/bash-completion/bash_completion although the latter seems to be just for the auto completion feature with the Tab?

Where should I make my changes?

Best Answer

In your .bashrc:

function process_command() {
  ... do something with $BASH_COMMAND ...
trap process_command DEBUG

For a good example see "Make gnome-terminal show the command running as title" on AskUbuntu.

To solve the original poster's request to run clear before the command and reset after the command, add to .bashrc:

function before_command() { 
  case "$BASH_COMMAND" in

function before_prompt() { reset ; }

trap before_command DEBUG

In man bash look for PROMPT_COMMAND and trap .-lp.

Related Question