检查rsync命令是否运行成功

下面的bash脚本每小时做一个文件夹的rsync

#!/bin/bash rsync -r -z -c /home/pi/queue root@server.mine.com:/home/foobar rm -rf rm /home/pi/queue/* echo "Done" 

但是我发现我的Pi从互联网上断开,所以rsync失败了。 所以它做了下面的命令,删除文件夹。 如何确定一个rsync命令是否成功,如果是,那么它可能会删除该文件夹。

通常情况下,如果任何Unix命令成功运行,它将返回0,在其他情况下,将返回非0。

看看可能与您的情况有关的退出代码的rsync,但我会这样做:

 #!/bin/bash rsync -r -z -c /home/pi/queue root@server.mine.com:/home/foobar && rm -rf rm /home/pi/queue/* && echo "Done" 

只有在一切正常的情况下,才能完成rm和echo。

其他方式做到这一点将通过使用$? 变量,它总是上一个命令的返回码:

 #!/bin/bash rsync -r -z -c /home/pi/queue root@server.mine.com:/home/foobar if [ "$?" -eq "0" ] then rm -rf rm /home/pi/queue/* echo "Done" else echo "Error while running rsync" fi 

请参阅man rsyncEXIT VALUES部分

你需要检查rsync的退出值

 #!/bin/bash rsync -r -z -c /home/pi/queue root@server.mine.com:/home/foobar if [[ $? -gt 0 ]] then # take failure action here else rm -rf rm /home/pi/queue/* echo "Done" fi 

这里的结果代码集: http : //linux.die.net/man/1/rsync

老问题,但我很惊讶没有人给出了简单的答案:
使用–remove-source-files rsync选项。
我想这正是你需要的。

从手册页:

 --remove-source-files sender removes synchronized files (non-dir) 

只有rsync完全成功传输的文件才被删除。

当不熟悉rsync的时候,很容易被搞糊涂–delete选项和–remove-source-files选项。 –delete选项删除目标端的文件。 更多信息在这里: https : //superuser.com/questions/156664/what-are-the-differences-between-the-rsync-delete-选项