开发者社区 问答 正文

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

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

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

展开
收起
a123456678 2016-06-16 15:19:37 2156 分享 版权
1 条回答
写回答
取消 提交回答
  • 最好避免使用 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; }
    2019-07-17 19:40:59
    赞同 展开评论
问答分类:
问答地址: