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

标签 bash shell

<分区>

我正在写一个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。)

有几种方法可以简化这一过程。

写一个函数

就像在其他编程语言中一样,公共(public)逻辑可以移到共享函数中。

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 中什么都不打印意味着成功。此外,任何失败的正常命令都会打印一条错误消息,因此您无需添加。

利用这两个事实,您可以使用 || exit 在命令失败时退出。您可以将 || 理解为“否则”。

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

使用-e

或者,您可以启用 -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'

关于bash - 检查命令是否成功使 shell 脚本很长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100045/

相关文章:

linux - 字符串在每个变量后重新开始 [Bash]

javascript - node.js shell 命令执行

linux - 如果编译器选项与以前使用的选项不同,则使目标过时

mysql - 将多个查询输出到单独的文件

git - CLI : implement something like git commit (open a text editor and get value)

linux - Docker Bash 提示不显示颜色输出

shell - 如何在 UNIX 中将两个行号之间的文本打印到新文件中

linux - 如何比较umask

bash - bash中的十六进制到二进制转换

bash - 源 shell 脚本到 makefile