Retry command until exitcode OK
So I recently created a script to clean up some messy M365 / Azure accounts, but ran in to a connectivity issue – every now and then the script would break due to timeouts due to a faulty internet connection on the given server.
Fixing the servers connection first was not an option and exception handling was out of the question with the ‘black box’ module I was using, so I had to find an other way to make the script retry at failure.
The script threw an exitcode at errors so a quick & dirty fix was the following oneliner:
fakeCommandName; until [[ $? -eq 0 ]]; do /usr/bin/php /opt/myscript.php; done
Using $? you will get last commands exitcode, so in short what this oneline does is simply;
- Run fake command that will throw an error exitcode
- Check if exitcode is 0 (it is not 0 since fakeCommandName does not exists)
- Loop with the real script until exitcode is 0.
Every time the connection breaks this loop will rerun the script until finally the script has finished successfuly