Check if rsync command ran successful
Solution 1
Usually, any Unix command shall return 0 if it ran successfully, and non-0 in other cases.
Look at man rsync for exit codes that may be relevant to your situation, but I'd do that this way :
#!/bin/bash
rsync -r -z -c /home/pi/queue [email protected]:/home/foobar && rm -rf rm /home/pi/queue/* && echo "Done"
Which will rm and echo done only if everything went fine.
Other way to do it would be by using $? variable which is always the return code of the previous command :
#!/bin/bash
rsync -r -z -c /home/pi/queue [email protected]:/home/foobar
if [ "$?" -eq "0" ]
then
rm -rf rm /home/pi/queue/*
echo "Done"
else
echo "Error while running rsync"
fi
see man rsync, section EXIT VALUES
Solution 2
Old question but I am surprised nobody has given the simple answer:
Use the --remove-source-files rsync option.
I think it is exactly what you need.
From the man page:
--remove-source-files sender removes synchronized files (non-dir)
Only files that rsync has fully successfully transferred are removed.
When unfamiliar with rsync it is easy to be confused about the --delete options and the --remove-source-files option. The --delete options remove files on the destination side. More info here: https://superuser.com/questions/156664/what-are-the-differences-between-the-rsync-delete-options
Solution 3
you need to check the exit value of rsync
#!/bin/bash
rsync -r -z -c /home/pi/queue [email protected]:/home/foobar
if [[ $? -gt 0 ]]
then
# take failure action here
else
rm -rf rm /home/pi/queue/*
echo "Done"
fi
Set of result codes here: http://linux.die.net/man/1/rsync
user1670816
Updated on July 16, 2022Comments
-
user1670816 almost 2 years
The following bash-script is doing a rsync of a folder every hour:
#!/bin/bash rsync -r -z -c /home/pi/queue [email protected]:/home/foobar rm -rf rm /home/pi/queue/* echo "Done"
But I found out that my Pi disconnected from the internet, so the rsync failed. So it did the following command, deleting the folder. How to determine if a rsync-command was successful, if it was, then it may remove the folder.
-
user1670816 almost 10 yearsShould I use
if [ "$?" -eq "0" ]
orif [[ $? -gt 0 ]]
? Because the latest is the resultcode regarding the rsync documentation. -
Benjamin Sonntag almost 10 yearsboth work fine. [ is a shell syntax, [[ is bash-specific, and the first compare the exit code to 0, the other one to non-zero, and the if is reverse, so both are working fine and doing exactly the same here \o/