shell命令返回值判断的方法有哪些

这篇文章主要介绍了shell命令返回值判断的方法有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇shell命令返回值判断的方法有哪些文章都会有所收获,下面我们一起来看看吧。

1.判断命令是否存在

优雅方法1

首先,检查命令是否有效的惯用方法直接在if语句中。

if command; then
    echo notify user OK >&2
else
    echo notify user FAIL >&2
    return -1
fi

(良好做法:使用>&2将消息发送给stderr。)

优雅方法2

将通用逻辑转移到共享函数中。

check() {
    local command=("$@")

    if "${command[@]}"; then
        echo notify user OK >&2
    else
        echo notify user FAIL >&2
        exit 1
    fi
}

check command1
check command2
check command3

优雅方法3

installed () {
        command -v "$1" >/dev/null 2>&1
}
if installed <command1>
then
       <command1>  xx
else
        <command1>  xxx
 fi

2.返回错误退出

1.|| exit退出

command1 || exit
command2 || exit
command3 || exit

2.使用-e

$  bash -e xx.sh
#!/bin/bash -e xx.sh
command1
command2
command3

3.set -e

$ bash xx.sh 
#!/bin/bash
set -e 
command1
command2
command3

3.返回错误提示

一般方法:

方法1

if do some command; then
    echo notify user OK
else
    echo notify user fail
    exit 255  # exit code must be unsigned short
fi

方法2

do some command
if [ $? -eq 0 ]; then
    echo notify user OK
else
    echo notify user FAIL
    return -1
fi

优雅方法

方法1

die() {
    local message=$1

    echo "$message" >&2
    exit 1
}

command1 || die 'command1 failed'
command2 || die 'command2 failed'
command3 || die 'command3 failed'

方法2(推荐)

warn () {
  echo "$@" >&2
}

die () {
  status="$1"
  shift
  warn "$@"
  exit "$status"
}

do some command && echo notify user OK || die 255 Notify user fail

关于“shell命令返回值判断的方法有哪些”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“shell命令返回值判断的方法有哪些”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接