Linux: Repeat last command until exit code is equal to 0

Scenario: we want to repeat the last entered command which fails until it returns a system code of 0, the reason that potentially exits with !=0 is because of network problem

solution: edit ~/.bashrc and enter

alias repeat='while [ $? -ne 0 ]; do $(fc -nl -1); done'

Now we need a tool to test if it works, we want a small tool to verify that the command will be executed until the exit code is 0, create file random.sh and enter

#!/bin/bash
RANDOM_INTEGER=$((RANDOM % 10+1))
if [ $(( RANDOM_INTEGER % 2 )) -eq 0 ]
then
echo "exit code 0"
exit 0
else
echo "exit code 1"
exit 1
fi

mark file as executable

$ chmod +x random.sh

Now if we run the file multiple times we will receive something like the following

kpatronas@NARCISSUS:~$ ./random.sh
exit code 1
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 1
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 1
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$

Lets glue everything together and check if we can run random.sh until exits with code 0, to do this run random.sh until it prints exit code 1

kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh
exit code 1
kpatronas@NARCISSUS:~$

Then run the random.sh like this

kpatronas@NARCISSUS:~$ ./random.sh ; repeat
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh ; repeat
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh ; repeat
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh ; repeat
exit code 0
kpatronas@NARCISSUS:~$ ./random.sh ; repeat
exit code 1
exit code 1
exit code 0

Notice that the first four times random.sh returned an exit code of 0, this caused repeat alias not to run, the fifth time repeat alias inserted into the while loop and exited loop when the random.sh returned an exit code of 0.

I hope you found my article useful :)

Written by

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store