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

use*_*026 5 bash shell

我正在编写一个 shell 安装脚本
在每个命令之后我需要检查命令是否成功 - 我必须通知用户失败的原因。
如果出现故障 - 安装无法继续,目前在我添加的每个命令之后

if [ $? -eq 0 ]; then  
Run Code Online (Sandbox Code Playgroud)

但这会为 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
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 6

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

if command; then
    echo notify user OK >&2
else
    echo notify user FAIL >&2
    return -1
fi
Run Code Online (Sandbox Code Playgroud)

(好的做法:使用 of>&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
Run Code Online (Sandbox Code Playgroud)

不要打印任何东西

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

利用这两个事实,您可以|| exit在命令失败时使用退出。你可以读||作“否则”。

command1 || exit
command2 || exit
command3 || exit
Run Code Online (Sandbox Code Playgroud)

-e

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

#!/bin/bash -e

command1
command2
command3
Run Code Online (Sandbox Code Playgroud)

不要打印任何东西

如果您确实想要错误消息,但没有成功消息也没关系,那么一个die()函数很受欢迎。

die() {
    local message=$1

    echo "$message" >&2
    exit 1
}

command1 || die 'command1 failed'
command2 || die 'command2 failed'
command3 || die 'command3 failed'
Run Code Online (Sandbox Code Playgroud)


sna*_*nap 2

我想你可以在函数内转移检查逻辑,例如:

checkLastCommand() {
     if [ $? -eq 0 ]; then
          echo notify user OK
     else 
          echo notify user FAIL
          exit -1 
     fi
 }
 do some command
 checkLastCommand
 do some command
 checkLastCommand
Run Code Online (Sandbox Code Playgroud)