`which`,但所有

ken*_*nny 30 path

我想大多数人都熟悉这个which命令,我经常使用它。我刚刚遇到了一种情况,我不仅好奇哪个命令在我的路径中是第一个,还想知道我所有路径中的所有命令的数量和位置。我尝试了 which 手册页(打字man which让我发笑),但什么也没看到。

Gil*_*il' 33

在某些系统上,which -a显示所有匹配项。如果您的 shell 是 bash 或 zsh¹,则可以type改用:type foo显示第一个匹配项并type -a foo显示所有匹配项。这三个命令typewhichwhence做几乎相同的事情; shell 和操作系统在可用性、选项以及它们报告的内容方面有所不同。type始终可用并显示所有可能的类似命令的名称(别名、关键字、shell 内置函数、函数和外部命令)。

显示所有匹配项的唯一完全可移植的方式是$PATH自己解析。这是一个执行此操作的 shell 脚本。如果您将其设为 shell 函数,请确保将函数主体括在括号中(以便更改IFSset -f不会转义函数),并更改exitreturn.

#!/bin/sh
set -f       # disable globbing
IFS=:        # break words at : only
not_found=1
for d in $PATH; do
  if [ -f "$d/$x" ] && [ -x "$d/$x" ]; then
    printf '%s\n' "$d/$x"
    not_found=0
  fi
done
exit $not_found
Run Code Online (Sandbox Code Playgroud)

¹ 或 ksh 93,根据文档,尽管 ksh 93s+ 2008-01-31 仅在我尝试时打印第一个匹配项。


Eli*_*ady 5

--all 或 -a 标志将显示路径中的所有匹配项和别名(至少在 Fedora、Ubuntu 和 CentOS 上):

which -a which
Run Code Online (Sandbox Code Playgroud)

在 AIX 和 Solaris 上,这将使您接近:

echo "$PATH" | sed -e 's/:/ /g' | \
while read -r p; do find "$p" -type f -name "which"; done
Run Code Online (Sandbox Code Playgroud)