検索

ホームページ  >  に質問  >  本文

linux - Shell(Bash)中如何判断是否存在某个命令

在编写bash时,如果要判断某条命令是否存在,应该如何写呢?
我尝试了如下的写法,不知道错误在哪里

if [ -n `which brew`]; then
 echo 'brew exist'
else
 echo 'brew does not exist'
fi

用来判断brew命令是否存在,可是明明没有brew,却总是显示 "brew exist"

怪我咯怪我咯2865日前733

全員に返信(3)返信します

  • PHP中文网

    PHP中文网2017-04-17 11:11:26

    最好避免使用 which,做为一个外部的工具,并不一定存在,在发行版之间也会有区别,有的系统的 which 命令不会设置有效的 exit status,存在一定的不确定性。

    Bash 有提供一些内建命令如 hash、type、command 也能达到要求。

    $ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
    $ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
    $ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }

    详见 http://stackoverflow.com/questions/59...

    返事
    0
  • PHP中文网

    PHP中文网2017-04-17 11:11:26

    which want_to_find > /dev/null 2>&1
    if [ $? == 0 ]; then
        echo "exist"
    else
        echo "dose not exist"
    fi

    返事
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:11:26

    if which brew 2>/dev/null; then
      echo "brew exists!"
    else
      echo "nope, no brew installed."
    fi

    which 在找不到命令时会输出「xxx not found」到 stderr 的。

    返事
    0
  • キャンセル返事