【问题标题】:Bash Centos7 "which" commandBash Centos7 "which" 命令
【发布时间】:2015-01-07 08:42:05
【问题描述】:

我意识到这可能是一个愚蠢的问题,但我安装了 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

任何帮助都将不胜感激......这对于谷歌来说即使不是不可能也很困难

【问题讨论】:

  • 缺少grepwhich 吗?
  • 顺便说一句,您的代码有几个错误。你想要的只是if ! type -p grep >/dev/null 2>&1; then echo "grep not found, installation aborted" >&2; fi
  • 非常不笨;我的 centos7 体验中缺少 makewhich 让我有点惊讶,所以谢谢你的提问。 @Wintermute 的回答对我很有教育意义。

标签: bash shell command centos7 yum


【解决方案1】:

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

yum whatprovides *bin/which

在这种特殊情况下,包被称为which,所以

yum install which

应该把它拉进去。

【讨论】:

    【解决方案2】:

    您可以使用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
    

    【讨论】:

    • 这是更好的解决方案。 which 是不可移植的,而 type 是 POSIX 强制要求并内置在 shell 中的。
    • type -P grep 输出路径到grep,正是which 所做的。
    • $? 的迂回显式检查仍然是单调和笨拙的。 if 和朋友们的目的是运行一个命令并检查它的退出状态;您几乎不需要明确检查 $? 是否为非零。任何看起来像cmd; if [ $? -ne 0 ] 的东西最好写成if ! cmd
    • 如何让type 输出命令的位置?例如,我通常想做cat $(which ansible),以检查python脚本内容。
    猜你喜欢
    • 1970-01-01
    • 2011-03-27
    • 2021-08-20
    • 2020-01-20
    • 2017-01-21
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多