5

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?

  • You want to run a command before each command, what will be run before that command? It's a recursion here – Anwar Nov 24 '16 at 12:35
  • @Anwar I meant run a command before each command written in the console. – Katu Nov 24 '16 at 12:55
  • That's a good opportunity to switch to Zsh, which can do this natively. In Bash it requires some tinkering; see superuser.com/questions/175799/… – fkraiem Nov 24 '16 at 13:27
  • Also see: unix.stackexchange.com/questions/44713/… – muru Nov 26 '16 at 7:39
7

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
        $PROMPT_COMMAND)
          ;;
       *)
          clear;
  esac
}

function before_prompt() { reset ; }

trap before_command DEBUG
PROMPT_COMMAND=before_prompt

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

| improve this answer | |
  • Would it be { clear; $BASH_COMMAND; reset; } ? – wjandrea Nov 25 '16 at 23:07
  • No. Please read the provided link and the manual. You cannot execute $BASH_COMMAND, it's provided for informative purposes only. What the original poster asked can be done by clearing the screen in a function called just before executing a command, and resetting the terminal in a function run before outputting the prompt. I have edited the answer to provide an example. – AlexP Nov 26 '16 at 6:22
  • @AlexP your answer is useful, however, I have tried it with the command date and found the following: Hitting enter correctly runs before_command and before_prompt. However, if I write the command ls and then hit enter, the before_command runs twice, once before and once after ls. The command before_prompt correctly runs once after ls. I'm still looking for a complete solution for this, any tips are much appreciated. – Katu Nov 28 '16 at 10:33
  • The function set as a DEBUG trap will run before any command is executed, which means that it will also run before $PROMPT_COMMAND. You can test $BASH_COMMAND to see whether the command to be run is $PROMPT_COMMAND or not. – AlexP Nov 28 '16 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.