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

标签 bash

假设我有:

>which -a foo
/bin/foo
/usr/bin/foo

我想要这样的东西:

>foo
Warning: multiple foo in PATH
... foo gets executed ...

这个功能今天真的可以为我节省很多时间。 我早该猜到这是在发生,但问题还不清楚 在开始时对我来说,我开始朝着完全相反的方向挖掘。

最佳答案

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

首先,您需要创建一个函数来检查 PATH 中的所有目录,并在其中查找您尝试运行的命令。 然后,您需要将此函数绑定(bind)到当前 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

使用示例:

$ . /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
$ 

关于bash - 在 bash 中执行命令时路径中有多个可执行文件时生成警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433111/

相关文章:

bash - 如何使 .bashrc 别名在 vim shell 命令中可用? (:! ...)

bash - 查找并替换为 sed

linux - 如何从 web 发送参数或指令到 linux 机器并在 web 中显示结果?

c++ - 无法使用 execlp 从管道读取

bash - unix中时间命令的开销

linux - Bash脚本移动具有特定名称的前N个文件

linux - 在bash中修改用户

bash - 如何将 && 与我自己的函数一起使用?

linux - 无法更改 tclsh 路径

bash - 是否可以使用 bash 在脚本中直接执行命令?