How to run some command before or after every Bash command entered from console?

I want to run a command, for example

echo "foobar";

After each command, entered by the user.

Two scenarios:

  • When the user enters a command, my global command should be executed, and later his command should be executed
  • When the user enters a command, his command should be executed, and later my global command should be executed

How to accomplish the above two scenarios?

NB: I don't want to use the prompt for this purpose, (leave the PS1 variable as is).


Solution 1:

As l0b0 suggests, you can use PROMPT_COMMAND to do your second request and you won't have to touch PS1.

To do your first request, you can trap the DEBUG pseudo-signal:

trap 'echo "foobar"' DEBUG

Solution 2:

For the second part you could use declare -r PROMPT_COMMAND="echo 'foobar'": It is executed just before the prompt is displayed. Beware that it will not be run for each command in for example a pipe or command group.

Beware that any solution to this has the potential to mess things up for the user, so you should ideally only call commands which do not output anything (otherwise any output handling is virtually impossible) and which are not available to the user (to avoid them faking or corrupting the output).