加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 检查命令是否成功使shell脚本很长

发布时间:2020-12-15 22:15:41 所属栏目:安全 来源:网络整理
导读:参见英文答案 Error handling in Bash????????????????????????????????????14个 我正在编写一个shell安装脚本 在每个命令之后我需要检查命令是否成功 – 我必须通知用户失败了什么. 如果出现故障 – 安装无法继续,目前在我添加的每个命令之后 if [ $? -eq 0
参见英文答案 > Error handling in Bash????????????????????????????????????14个
我正在编写一个shell安装脚本
在每个命令之后我需要检查命令是否成功 – 我必须通知用户失败了什么.
如果出现故障 – 安装无法继续,目前在我添加的每个命令之后

if [ $? -eq 0 ]; then

但是这为shell脚本的每个命令增加了6行
有没有办法缩短这个检查?

样品:

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

解决方法

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

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

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

有几种方法可以简化这一点.

写一个函数

就像在其他编程语言中一样,可以将通用逻辑移动到共享功能中.

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

不要打印任何东西

在惯用shell脚本中,成功的命令不会打印任何内容.什么都不打印意味着UNIX的成功.此外,任何失败的良好命令都会打印错误消息,因此您无需添加错误消息.

利用这两个事实,你可以使用||每当命令失败时退出退出.你可以阅读||作为“否则”.

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

你看

或者,您可以启用-e shell标志,以便在命令失败时退出shell.那你根本不需要任何东西.

#!/bin/bash -e

command1
command2
command3

不要打印任何东西

如果你确实想要错误消息,但没有成功消息就可以了,die()函数很受欢迎.

die() {
    local message=$1

    echo "$message" >&2
    exit 1
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读