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


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

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

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

Linux shell bash

平静的代表 11 years, 2 months ago

最好避免使用 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...

Mr_少俠 answered 11 years, 2 months ago

Your Answer