Shell下判断一个命令是否存的最好方法

[attach]1617[/attach] 通常情况下,我们利用Shell脚本写一些服务启动脚本或者软件的初始化启动脚本的时候,经常会依赖一些外部的目录,比如Linux下解压zip压缩包你会依赖unzip命令等情况。那在shell下我们怎么判断一个命令是否存在呢,看完下面的分析你就了解了。   1、which非SHELL的内置命令,用起来比内置命令的开销大,并且非内置命令会依赖平台的实现,不同平台的实现可能不同。
[root@node1 ~]# type scp
scp is /usr/bin/scp
[root@node1 ~]# type command
command is a shell builtin
[root@node1 ~]# type which
which is aliased to `alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
从上面可以看出command为内置命令,而which非内置命令。   2、很多系统的which并不设置退出时的返回值,即使要查找的命令不存在,which也返回0
[root@node1 ~]# which ls
/usr/bin/ls
[root@node1 ~]# echo $?
0
[root@node1 ~]# which www
no www in /usr/bin /bin /usr/sbin /sbin /usr/local/bin /usr/local/bin /usr/local/sbin /usr/ccs/bin  
[root@node1 ~]# echo $?
0
所以许多系统的which实现,都偷偷摸摸干了一些“不足为外人道也”的事情。   所以,不要用which,可以使用下面的方法:
$ 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; }
The following is a portable way to check whether a command exists in PATH and is executable:

[ -x "$(command -v foo)" ]

Example:

if ! [ -x "$(command -v git)" ]; then
  echo 'Error: git is not installed.' >&2
  exit 1
fi
更精彩的分析参考:http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script

0 个评论

要回复文章请先登录注册