版权声明:转载请注明出处,谢谢。 https://blog.csdn.net/butterfly5211314/article/details/84766207
shell编程中如何判断一个命令是不是存在呢?
为了方便说明, 下面用 cmd 来表示要判断的命令.
1. 直接执行
最直观的, 直接执行它, 如果cmd不存在, 肯定会报错, 可能通过$?
是不是0来判断:
$ ls
anaconda-ks.cfg dev-scripts install.log install.log.syslog
$ echo $?
0
$ xxx
-bash: xxx: command not found
$ echo $?
127
不过这样有个很大的问题, 就是cmd如果要求最少传入一个参数(比如rm
),
直接执行就会报错, 虽然cmd可能是存在的.
2. 用which
, command
, whereis
type
等
可以用which
, command
, whereis
type
来判断.
-
用
type
的简单示例:$ type type type is a shell builtin $ type ls ls is aliased to `ls --color=auto' $ echo $? 0 $ type xxx -bash: type: xxx: not found $ echo $? 1
type type
显示说,type
是一个shell内置的命令, 然后type cmd
,
根据$?
就可以判断cmd
是不是存在了. -
用
which
: 源代码地址function isCmdExist() { local cmd="$1" if [ -z "$cmd" ]; then echo "Usage isCmdExist yourCmd" return 1 fi which "$cmd" >/dev/null 2>&1 if [ $? -eq 0 ]; then return 0 fi return 2 }
-
用
command
在折腾vim插件时, 看到别人写的program_exists() { local ret='0' command -v $1 >/dev/null 2>&1 || { local ret='1'; } # fail on non-zero return value if [ "$ret" -ne 0 ]; then return 1 fi return 0 }
欢迎补充指正!