Bash Centos7中的"which"命令

23

我知道这可能是一个愚蠢的问题,但我安装了一个Centos-7最小化服务器,并且缺少"which"命令。 我有一个需要它的脚本,但我无法找到安装它的yum包。 下面的代码来自一个make文件。

which grep > /dev/null 2> /dev/null

if test "$?" != "0"
then
    echo "\"grep\" command not found."
    echo "Installation is aborted."
    exit 1
fi

非常感谢您的帮助,这个问题很难在Google上找到答案。


grepwhich缺失吗? - Odi
顺便提一下,你的代码有几个 bug。你只需要这样写:if ! type -p grep >/dev/null 2>&1; then echo "grep not found, installation aborted" >&2; fi - tripleee
非常不傻;我有点惊讶于我的CentOS7体验中缺少makewhich,所以感谢你的提问。@Wintermute的回答对我很有启发。 - jgreve
2个回答

33

要在CentOS中查找软件包,请使用yum whatprovides命令:

yum whatprovides *bin/which

在这种特定情况下,包被称为which,因此

yum install which

应该把它拉进来。


10

你可以使用type命令代替which命令。

type grep > /dev/null 2> /dev/null
if test "$?" != "0"
then
    echo "\"grep\" command not found."
    echo "Installation is aborted."
    exit 1
fi

2
这是更好的解决方案。which 是不可移植的,而 type 是 POSIX 强制规定并内置于 shell 中的。 - tripleee
3
type -P grep 的输出路径传递给 grep,这正是 which 所做的。 - Étienne Bersac
$? 的迂回显式检查仍然不够惯用和笨拙。if 和相关语句的目的是运行一个命令并检查其退出状态;你几乎永远不需要显式地检查 $? 是否非零。任何看起来像 cmd; if [ $? -ne 0 ] 的东西都最好写成 if ! cmd - tripleee
你如何让 type 仅输出命令的位置?例如,我经常想要执行 cat $(which ansible) 来检查 Python 脚本内容。 - AlanSE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接