Repeating Failed Linux Command on Bash

I was in need of backing up a lot of data in a hurry.  I used rsync between the file server and a locally mounted USB drive, but for some reason the command kept failing.  It had something to do with checksum calculation, but it may have had something to do with how hardware is set up, so I didn’t wish to go looking for the very root of the problem; I just needed to back things up.

I simply decided to repeat the rsync command when it failed, until it succeeded syncing all files. Here’s a simple example script to do this:


CMD="rsync -av --delete remote:/scrXX/dir /media/usb/storage"

while :
    echo $CMD ;
    $CMD ;

    if [ $? -eq 0 ]; then

    echo "... redo ..." ;

echo "Done." ;

The gist of the Bash trick is to use “$?”, which stores the return code of the last executed process.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

2 Responses to Repeating Failed Linux Command on Bash

  1. ScottB says:

    I’m having a similar issue (failing server, dodgy ethernet port and resetting sata controller). I was about to script something up in bash but I like keep it to a sweet and simple compound command. You can save yourself a script and do it on the command line with:

    until rsync -av –delete remote:/scrXX/dir /media/usb/storage ; do echo “status: $?”; done;

    Will keep doing the rsync until exit status is 0 (true).

Leave a Reply

Your email address will not be published. Required fields are marked *