DEV Community

Mayeu
Mayeu

Posted on • Originally published at mayeu.me

6 1

How to run a command in your shell until it succeed

I am regularly copying big files over the internet via rsync, and since I am travelling a lot, I don't generally have access to stable internet connection, so I end-up rerunning the command multiple times until it succeeds.

Turns out there is a better way. Of course you could use while and test the return of the command, but that sounds like a lot of work for a ad hoc command. But I am lazy and I recently discovered that an until command exists!

Pretty straightforward to use:

$ until <put your command here>; do echo "Retrying at `date -Iminutes`"; done
Enter fullscreen mode Exit fullscreen mode

So with rsync you get:

$ until rsync -aP src:/path/to/src dest/; do echo "Retrying at `date -Iminutes`"; done
Enter fullscreen mode Exit fullscreen mode

And if you are really lazy, just create an alias (left as an exercise ;) ).

This post was originally published on mayeu.me.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (4)

Collapse
 
marleythemanzan profile image
Alexander C. Wilcots

To maximize laziness, you can make it into a function called retry() and have the rsync command as the first argument.

Collapse
 
mayeu profile image
Mayeu

Yup, but I'm too lazy to maximize my laziness :D

Anyway, if somebody is wondering, something like that should do it (ugly, may be unsafe, you are warned):

function retry() {
  until $1 ;
  do
    echo "Retrying at `date -Iminutes`";
  done
}
Collapse
 
_ajduke profile image
Abhijeet S. Sutar

How about this CLI tool - github.com/nvbn/thefuck

Collapse
 
mayeu profile image
Mayeu

Hey, thank you for your reply :)

This is not really the same, thefuck correct spelling errors of the previous command you do. While using until will perpetually re-run the command until the exit code is 0 (i.e.: until it is a success).

In the case of rsync that allow you to continue the download until it succeed :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay