linux shell 判断一个命令是否存在

首先要说明的是,不要使用which来进行判断,理由如下:

1、which非SHELL的内置命令,用起来比内置命令的开销大,并且非内置命令会依赖平台的实现,不同平台的实现可能不同。

  1. # type type
  2. type is a shell builtin
  3. # type command
  4. command is a shell builtin
  5. # type which
  6. which is hashed (/usr/bin/which)

2、很多系统的which并不设置退出时的返回值,即使要查找的命令不存在,which也返回0

  1. # which ls
  2. /usr/bin/ls
  3. # echo $?
  4. 0
  5. # which aaa
  6. no aaa in /usr/bin /bin /usr/sbin /sbin /usr/local/bin /usr/local/bin /usr/local/sbin /usr/ccs/bin /usr/openwin/bin /usr/dt/bin
  7. # echo $?
  8. 0

3、许多系统的which实现,都偷偷摸摸干了一些“不足为外人道也”的事情

所以,不要用which,可以使用下面的方法:

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

 

 

(0)

相关推荐