astropanic
astropanic

Reputation: 10939

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:

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).

Upvotes: 29

Views: 10410

Answers (2)

l0b0
l0b0

Reputation: 58788

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).

Upvotes: 10

Dennis Williamson
Dennis Williamson

Reputation: 359955

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

Upvotes: 17

Related Questions