1. 程式人生 > >shell程式設計判斷一個命令是否存在?

shell程式設計判斷一個命令是否存在?

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 }

歡迎補充指正!