简体   繁体   English

执行命令时运行脚本,不管命令的参数如何

[英]Run script when a command is executed irrespective of the command's arguments

rm -rf
rm -r
rm -f
rm

When any of these commands are run I want them to run a certain script. 当运行这些命令中的任何一个时,我希望它们运行某个脚本。

Something like alias ?='some_script.sh' alias ?='some_script.sh'

(the question mark in this case means the rm command with any arguments.) (在这种情况下,问号表示带有任何参数的rm命令。)

How can this be done? 如何才能做到这一点? I don't HAVE to use aliases, anything that works is fine. 我不必使用别名,任何有效的东西都可以。

Don't use an alias; 不要使用别名; define a function: 定义一个函数:

rm () {
    some_script.sh
    command rm "$@"
}

The standard disclaimer when modifying the behavior of rm in any way applies. 以任何方式修改rm行为时的标准免责声明适用。 Don't do this is some_script.sh is intended to be a safety net of some kind. 不要这样做是some_script.sh旨在成为某种安全网。 You may become reliant on it, and be unpleasantly surprised if you run rm on a machine without this safety net installed. 您可能会依赖它,如果您在未安装此安全网的计算机上运行rm ,则会感到不快。

If your requirement is to run the script on every bash command, then best way is to append it to a special variable in bash , which gets executed every time a command is entered in the prompt. 如果您的要求是在每个bash命令上运行脚本,那么最好的方法是将它附加到bash的特殊变量,每次在提示符中输入命令时都会执行该变量。

The PROMPT_COMMAND variable, all you need to do is append your script some_script.sh to it like PROMPT_COMMAND变量,您需要做的就是将脚本some_script.sh附加到它上面

$ PROMPT_COMMAND+="some_script.sh;"

Or if you want to script only for the command rm , then keeping an alias is the best way to do it. 或者,如果您只想为命令rm编写脚本,那么保留别名是最好的方法。 Add the line in your ~.bashrc and source it after making the change. ~.bashrc添加该行,并在进行更改后将其source

alias rm="some_script.sh; rm"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在bash脚本中运行命令,从csv文件中获取它的参数 - How to run a command within a bash script which gets it's arguments from a csv file 如果从 shell 脚本执行,cp 命令将不会运行 - cp command won't run if executed from shell script 从tty和脚本执行时,Awk命令的结果不同 - results of Awk command different when executed from a tty versus a script 如何运行 shell 脚本来显示命令行参数? - how to run shell script to display command line arguments? 从另一个 bash 脚本运行名为 arguments 的命令行 - Run command line with named arguments from another bash script 当执行“ sudo -s”命令时,c程序挂起/循环 - c program hangs/loops when “sudo -s” command is executed 将命令的输出存储在变量中,其中命令已经执行/存储在它自己的变量中 - bash脚本 - Store output of command in variable where the command is already executed/stored in it's own variable - bash script 在Linux上执行其他命令时执行命令 - Execute a command when another command is executed on linux 通过命令行执行时,PHP脚本无法正常工作,但从浏览器执行时,PHP脚本可以正常工作 - PHP script wont work when executed via command line but work fine when executed from browser 将命令行参数传递给bash脚本命令 - Passing command line arguments in to a bash script command
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM