首页 > 开发 > linux > 正文

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

2017-09-11 20:33:30  来源: 网友分享

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

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

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

解决方案

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