Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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)

rsync
while(is syncing){
    sleep 10
}
tar

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

Thanks for your help.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin

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

if [ $? != "0" ]
  then
   echo "There was a problem"
  else
   tar zcf /var/backups/home-`date +%Y%m%d`.tar.gz /location/of/local/folder
 fi
share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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