shell编程判断一个命令是否存在?

版权声明:转载请注明出处,谢谢。 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
    }
    

欢迎补充指正!

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/84766207
今日推荐