Bash 在变量中存储rsync错误

Bash 在变量中存储rsync错误,bash,ubuntu-14.04,rsync,Bash,Ubuntu 14.04,Rsync,我编写了一个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/"

我编写了一个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)
这将捕获已执行命令的stdout,但我认为您需要stderr。因此,更好的方法可能是通过管道将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
您好,
rsync\u error=$(…)
对我不起作用,但第二部分起作用:)非常感谢@Epodax没问题:)我没想到
$()
位会出现,但我很高兴另一位出现了:D