gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:59:59 25 4
gpt4 key购买 nike

假设我有:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com