在bash中执行命令时,路径中的多个可执行文件时生成警告

nsh*_*shy 6 bash

说我有:

>which -a foo
/bin/foo
/usr/bin/foo
Run Code Online (Sandbox Code Playgroud)

我想要的东西:

>foo
Warning: multiple foo in PATH
... foo gets executed ...
Run Code Online (Sandbox Code Playgroud)

这个功能今天真的让我节省了很多时间.我应该猜到这种情况发生得比较早,但是在开始时我的问题并不清楚,我开始向相反的方向挖掘.

Igo*_*bin 6

好吧,你可以做到,但它并不像你想象的那么容易.

首先,您需要创建一个函数来检查PATH中的所有目录,并查看您尝试运行的命令.然后,您需要将此函数绑定到当前shell的DEBUG陷阱.

我写了一个小脚本来做到这一点:

$ cat /tmp/1.sh

check_command()
{
    n=0
    DIRS=""
    for i in $(echo $PATH| tr : " ")
    do 
        if [ -x "$i/$1" ]
        then 
            n=$[n+1]
            DIRS="$DIRS $i"
        fi
    done
    if [ "$n" -gt 1 ]
    then
      echo "Warning: there are multiple commands in different PATH directories: "$DIRS
    fi
}

preexec () {
    check_command $1
}
preexec_invoke_exec () {
    [ -n "$COMP_LINE" ] && return  # do nothing if completing
    local this_command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"`;
    preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG
Run Code Online (Sandbox Code Playgroud)

用法示例:

$ . /tmp/1.sh
$ sudo cp /bin/date /usr/bin/test_it
$ sudo cp /bin/date /bin/test_it
$ test_it
Warning: there are multiple commands in different PATH directories:  /usr/bin /bin
Wed Jul 11 15:14:43 CEST 2012
$ 
Run Code Online (Sandbox Code Playgroud)

  • 而不是迭代`$ PATH`,你可以使用`type -pa"$ 1"`.您也可以使用`$ BASH_COMMAND`而不是解析`history`.`preexec`函数必须在另一个上下文中起作用,但它在这里是无关紧要的. (2认同)