bash - 我的美元?命令成功代码失败,为什么?

标签 bash

在我的 bash 脚本中,如果 rsync 在放弃之前失去与目的地的连接,我会尝试重试 10 次。

我知道这段代码会捕获所有错误,但我现在可以接受。

我的代码是:

lops="0"
while true; do
    let "lops++"
    rsync $OPT $SRCLINUX $TRG 2>&1 | tee --append ${LOGFILE}
    if [ "$?" -eq "0" ]; then
        echolog "rsync finished WITHOUT error after $lops times"
        break 
    else
        echolog "Re-starting rsync for the ${lops}th time due to ERRORS"
    fi
    if [[ "$lops" == "10" ]]; then
        echolog "GAVE UP DUE TO TOO MANY rsync ERRORS - BACKUP NOT FINISHED"
        break 
    fi
done

它没有按预期工作,这是第一个错误发生的情况:

TDBG6/
rsync: connection unexpectedly closed (131505 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.1]
rsync finished WITHOUT error after 1 times

这是因为 $?包含 tee 的返回值,不是 rsync?

我该如何解决这个问题? (我个人是 Linux 语法受限:)

最佳答案

我看到至少有两种可能性可以解决您的问题:

  1. 使用PIPESTATUS:

    An array variable containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

    用作:

    rsync $OPT $SRCLINUX $TRG 2>&1 | tee --append ${LOGFILE}
    if (( PIPESTATUS[0] == 0 )); then
    
  2. 使用 rsync--log-file 选项。

注意事项:

  • 您的代码中缺少很多引号!
  • 不要使用大写的变量名。
  • 不要使用 let 并使用 ((...)) 进行算术运算。

关于bash - 我的美元?命令成功代码失败,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243644/

相关文章:

bash - 在模式之后将多行文本从文件插入到另一个文件

linux - grep 变量和空格的问题

linux - 在 Awk split(for 循环)中运行 Sed 命令

c - 编写 Linux shell 时管理标准输出/标准输入

ruby - 从 crontab 运行 bundle exec

linux - 使用 sed 将 crontab 文件中的文本替换为斜线

linux - 如何使用字符串替换重命名Linux目录中的所有文件?

linux - 空闲 bash 脚本,直到记录 CTRL+c 事件

linux - 为什么该命令的输出在 Sh 和 Bash 之间不同?

linux - 如何在多台机器上执行 ps 来监控它们的性能