Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you run a command in bash over and over until success?

People also ask

How do I rerun a command in bash?

Just press the Ctrl and P keys together to fill the prompt with the last executed command and you are ready to go. This method works in bash perfectly even after closing the terminal, but it might not work in zsh after closing the session.

Does bash do until loop?

In bash for, while, and until are three loop constructs. While each loop differs syntactically and functionally their purpose is to iterate over a block of code when a certain expression is evaluated. Until loop is used to execute a block of code until the expression is evaluated to be false.


until passwd
do
  echo "Try again"
done

or

while ! passwd
do
  echo "Try again"
done

You need to test $? instead, which is the exit status of the previous command. passwd exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)

passwd
while [ $? -ne 0 ]; do
    passwd
done

With your backtick version, you're comparing passwd's output, which would be stuff like Enter password and confirm password and the like.


To elaborate on @Marc B's answer,

$ passwd
$ while [ $? -ne 0 ]; do !!; done

Is nice way of doing the same thing that's not command specific.


If anyone looking to have retry limit:

max_retry=5
counter=0
until $command
do
   sleep 1
   [[ counter -eq $max_retry ]] && echo "Failed!" && exit 1
   echo "Trying again. Try #$counter"
   ((counter++))
done