如何在从控制台输入的每个 Bash 命令之前或之后运行一些命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4585397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:11:34  来源:igfitidea点击:

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

bashcommand-line

提问by astropanic

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

注意:我不想为此目的使用提示(保留 PS1 变量原样)。

采纳答案by Paused until further notice.

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

正如 l0b0 所建议的那样,您可以使用PROMPT_COMMAND来执行第二个请求,而不必触摸PS1

To do your first request, you can trapthe DEBUGpseudo-signal:

要执行您的第一个请求,您可以trap使用DEBUG伪信号:

trap 'echo "foobar"' DEBUG

回答by l0b0

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.

对于第二部分,您可以使用declare -r PROMPT_COMMAND="echo 'foobar'":它在提示显示之前执行。请注意,它不会针对管道或命令组中的每个命令运行。

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

请注意,对此的任何解决方案都有可能给用户带来麻烦,因此理想情况下,您应该只调用不输出任何内容(否则几乎不可能进行任何输出处理)并且用户无法使用的命令(以避免它们伪造或破坏输出)。