Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeatedly run a shell command until it fails?

Tags:

bash

People also ask

What is until loop in shell script?

Until loop is used to execute a block of code until the expression is evaluated to be false. This is exactly the opposite of a while loop. While loop runs the code block while the expression is true and until loop does the opposite.

How do I stop a shell script from failing the command?

Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.


while takes a command to execute, so you can use the simpler

while ./runtest; do :; done

This will stop the loop when ./runtest returns a nonzero exit code (which is usually indicative of failure).

To further simplify your current solution though, you should just change your untilfail script to look like this:

#!/bin/bash

while "$@"; do :; done

And then you can call it with whatever command you're already using:

untilfail ./runTest --and val1,val2 -o option1 "argument two"

If you don't want to wrap a complex pipe line into a shell script or function then this works:

while true; do 
  curl -s "https:..." | grep "HasErrors.:true"
  if [[ "$?" -ne 0 ]]; then 
    break
  fi
  sleep 120
done

The HTTP request in this case always returns 200 but also returns some JSON which has an attribute "HasErrors":true when there is an error.


Having had a similar problem in a system that had shell retry logic duplicated everywhere I made a dedicated tool to solve this called "retry":

retry --until=fail ./runtest

A more complex example:

retry --until=fail --message="test succeeded" --delay=1 ./runtest

Tool available from https://github.com/minfrin/retry.