I'm stuck at the first hurdle!

I want to run a couple of commands from a bash script. First something like this to rsync some directories:

rsync -e ssh -az user-whatever@website.com:/home /location/of/local/folder

Then something like this to tar and copy the files somewhere else:

cd /location/of/local/folder
tar zcf /var/backups/home-`date +%Y%m%d`.tar.gz home

I hope this is making sense.

The problem is that obviously I wish for the rsync to finish before the directory is tar'd. So is there a bit of code I can use to make sure that rsync has finished before running the tar command?

e.g. (pseudo code)

while(is syncing){
    sleep 10

Or will my .sh script only run the next line after the first line has finished and exited?


Commands in a shell script are executed sequentially. If your first command is rsync, the next command will not execute until rsync completes.

What you want to be sure of is that rsync finishes successfully before continuing to the next command.

This is not the most elegant solution, but the easiest to implement.

rsync -e ssh -az user-whatever@website.com:/home /location/of/local/folder &&\
tar zcf /var/backups/home-`date +%Y%m%d`.tar.gz /location/of/local/folder

Keep in mind this will only work if the exit status of rsync is 0. Any other exit status and command 2 will not run.

AND and OR lists are sequences of one of more pipelines separated by the &&
and  ||  control operators, respectively.  AND and OR lists are executed 
with left associativity.  An AND list has the form
    command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero.

You could add more intelligence to your script if you performed different actions based on the rsync EXIT VALUES.


rsync -e ssh -az user-whatever@website.com:/home /location/of/local/folder

if [ $? != "0" ]
   echo "There was a problem"
   tar zcf /var/backups/home-`date +%Y%m%d`.tar.gz /location/of/local/folder
  • This is a brilliant and insightful answer. Thank you very much for taking the time. :) You've really helped me. Thank you. – Thomas Clayson May 8 '12 at 8:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.