Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 537
astropanic Avatar asked Jan 03 '11 14:01

astropanic


People also ask

How do I run multiple commands in bash script?

The Operators &&, ||, and ; The first logical operator we will be looking at will be the AND operator: &&. In Bash, it is used to chain commands together. It can also be used to run two different scripts together.


1 Answers

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 
like image 142
Dennis Williamson Avatar answered Sep 20 '22 19:09

Dennis Williamson