Check if rsync command ran successful

user1670816 picture user1670816 · Jun 27, 2014 · Viewed 32.9k times · Source

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.

Answer

Benjamin Sonntag picture Benjamin Sonntag · Jun 27, 2014

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