在变量中存储 rsync 错误

Store rsync error in variable

我编写了一个 bash 脚本来将备份与本地存储同步,该脚本会检查在脚本执行当天是否进行了备份,如果是则进行同步。

我这样做是为了如果意外(或其他方式)从原始位置删除所有备份,下次同步时不会删除第二个存储上的同步备份。

#!/bin/bash
files_found=`ssh user@xx.xx.xx.xx "find /home/data_folder/test* -type f -mtime -1"`

rsync_to_location="/home/test_folder/";     
rsync_from_location="/home/data_folder/";


if [ "$files_found" = 0 ]; then
    echo "File not found!"
    send_error=`ssh user@xx.xx.xx.xx "echo 'This is the message body' | mail -s 'This is the subject' user@localhost"`
else
    echo "Files found!"
    rsync -arzt --ignore-existing --delete --max-delete=1 -e 'ssh' user@xx.xx.xx.xx:$rsync_from_location $rsync_to_location

    if [[ $? -gt 0 ]]; then
        send_error=`ssh user@xx.xx.xx.xx "echo 'This is the message body' | mail -s 'This is the subject' earmaster@localhost"`
    fi
fi

现在我的问题是,如果 rsync 失败(最多删除),我如何存储该消息并将其与邮件一起发送?

我试过

rsync_error="rsync -arzt --ignore-existing --delete --max-delete=1 -e 'ssh' user@xx.xx.xx.xx:$rsync_from_location $rsync_to_location"

然后将$rsync_error添加到邮件调用中,但似乎不起作用

您在此处放置的行只会将该命令存储为字符串,而不是 运行。

rsync_error="rsync -arzt --ignore-existing --delete --max-delete=1 -e 'ssh' user@xx.xx.xx.xx:$rsync_from_location $rsync_to_location"

要捕获其输出,您需要像这样将其放在 $( ) 中。

rsync_error=$(rsync -arzt --ignore-existing --delete --max-delete=1 -e 'ssh' user@xx.xx.xx.xx:$rsync_from_location $rsync_to_location)

这将捕获已执行命令的标准输出,但我假设您需要标准错误。因此,更好的方法可能是将 stderr 通过管道传输到文件并以这种方式处理输出。

# rsync err output file
ERR_OUTPUT="/tmp/rsync_err_$$"
# When the script exits, remove the file
trap "rm -f $ERR_OUTPUT" EXIT

# Use 2> to direct stderr to the output file
rsync -arzt --ignore-existing --delete --max-delete=1 -e 'ssh' user@xx.xx.xx.xx:$rsync_from_location $rsync_to_location 2> "$ERR_OUTPUT"

# Do what ever with your error file