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 exists…

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 enteralias 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 followingkpatronas@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 1kpatronas@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 thiskpatronas@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 :)

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…