shell程式設計判斷一個命令是否存在?
阿新 • • 發佈:2019-01-10
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
歡迎補充指正!