Tuesday, February 21, 2012

Run a command until it is successful

During my travel, I was often in places whit bad Internet connections. Specially my uploads of pictures where often interrupted. I wrote a simple script which just executes the same command until it ends whit a success. It is very basic but did the job for me:

#!/bin/sh
tries=0

while [ "$exit" != "0" ]
do
 tries=`expr $tries + 1`
 echo -n "Try $tries on "
 date
 rsync -avzP "source" "destination"
 exit=$?
 echo $tries Exit $exit
 sleep 5
done

Save it to a file, upload.sh for example and make it executable:

chmod a+x upload.sh

Some times I used Windows for the upload, so here is almost the same as a batch file:

@echo off

:run
rsync.exe -avzP "source" "destination"
if ERRORLEVEL 1 goto run

UPDATE: I wrote a updated, all purpose script which I named tryuntilsuccess. It takes all parameters as the command to actually run for as many times until it returns 0.

#!/bin/sh
# tryuntilsuccess v 1.0
# http://codeatrandom.blogspot.com/2012/02/run-command-until-it-is-successful.html

tries=0
echo
echo Try: $@

while [ "$exit" != "0" ]
do
 tries=`expr $tries + 1`
 echo -n "Try $tries on "
 date
 $@
 exit=$?
 echo Try $tries give Exit $exit
 [ $exit != 0 ] && sleep 5
done

echo -----------------

No comments:

Post a Comment