我怎么可以拦截包含特定字符串命令? [英] How can I intercept commands that contain a certain string?

查看:161
本文介绍了我怎么可以拦截包含特定字符串命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,它发生,我认为我在执行某些命令,只有在事后我才知道我发​​错了参数的命令(如Heroku的应用程序的重新启动)。我想修改的bash以这样一种方式,如果它看到含有一定的字符串命令,它会提示我是否敢肯定与否。例如(想象中的字符串是腾邦):

Sometimes, it happens to me that I'm executing certain commands, and only afterwards I realize that I sent the wrong parameter to a command ( like a restart of a Heroku application ). I'd like to modify bash in such a way that if it sees a command containing a certain string, it will prompt me whether I'm sure or not. For example ( imagine the string is tempus ):

$ heroku restart --app tempus

现在,我想的bash提示我一个Y / N提示,如果我输入,才把我想它要执行的命令。如果键入N,该命令将不会被执行。我怎么能解决这个问题?

Now, I'd like bash to prompt me with a Y/N prompt, and if I type y, only then I'd like it to execute the command. If I type N, the command will not be executed. How could I handle this problem?

推荐答案

我不知道任何方式拦截所有的bash命令,但你可以拦截predetermined使用下面的技巧命令。

I don't know of any way to intercept all bash commands, but you can intercept predetermined commands using the following trick.


  1. 创建一个目录(比如〜/拦截),并将其设置为 $ PATH中的第一项

  2. 与您要拦截和命令列表的完整路径的实际命令创建在该目录下面的脚本

  1. Create a directory (say ~/interception) and set it as the first entry in $PATH
  2. Create the following script in that directory with a list of commands you wish to intercept and the full path to the actual command

[bash]$ cat intercept.sh
#!/bin/bash

# map commands to full path
declare -A COMMANDS
COMMANDS[heroku]=/usr/bin/heroku
COMMANDS[grep]=/bin/grep
# ... more ...

CMD=$(basename $0)  # command used to call this script

if [[ ! -z "${COMMANDS[$CMD]+x}" ]]; then  # mapping found
  # Do what you wish here. You can even modify/inspect the params.
  echo "intercepted $CMD command... "

  ${COMMANDS[$CMD]} $@   # run actual command with all params
else
  echo "Unknown command $CMD"
fi


  • 在同一目录下,创建一个使用你想拦截的命令名称符号链接到该脚本

  • In the same directory, create symlinks to that script using the name of the commands you wish to intercept

    [bash]$ ln -s intercept.sh grep
    [bash]$ ln -s intercept.sh heroku
    


  • 现在,每次调用命令时,该脚本是通过符号链接调用,那么它可以调用实际的命令之前做你的投标。

    Now, each time you call the command, that script is invoked via the symlink and it can then do your bidding before calling the actual command.

    您可以通过从配置文件的采购 $ COMMANDS 进一步扩大这一点,并帮助创建命令增加配置文件,并创建/删除符号链接。然后,你就可以使用以下命令来管理谁设置:

    You can extend this further by sourcing the $COMMANDS from a config file and create helper commands to augment the config file and create/remove the sym links. You would then be able to manage the who setup using commands such as:

    intercept_add `which heroku`
    intercept_remove heroku
    intercept_list
    

    这篇关于我怎么可以拦截包含特定字符串命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆