How to run some command before or after every Bash

2019-01-08 22:59发布

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

2条回答
贼婆χ
2楼-- · 2019-01-08 23:11

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-08 23:35

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
查看更多
登录 后发表回答