[SHELL]判斷一個命令是否存在

command -v  db2 |wc -l
執行命令返回結果爲0,則表示可以調用db2命令

command -v  db2 |wc -l
執行命令返回結果爲1,則表示不可以調用db2命令,需要配置用戶環境變量

首先要說明的是,不要使用which來進行判斷,理由如下:
1、which非SHELL的內置命令,用起來比內置命令的開銷大,並且非內置命令會依賴平臺的實現,不同平臺的實現可能不同。
# type type
type is a shell builtin
# type command
command is a shell builtin
# type which
which is hashed (/usr/bin/which)
2、很多系統的which並不設置退出時的返回值,即使要查找的命令不存在,which也返回0

# which ls
/usr/bin/ls
# echo $?
0
# which aaa
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
# echo $?
0

3、許多系統的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; }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章