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

BashCommandWhile Loop

Bash Problem Overview


I have a script and want to ask the user for some information, but the script cannot continue until the user fills in this information. The following is my attempt at putting a command into a loop to achieve this but it doesn't work for some reason:

echo "Please change password"
while passwd
do
    echo "Try again"
done

I have tried many variations of the while loop:

while `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more

But I can't seem to get it to work.

Bash Solutions


Solution 1 - Bash

until passwd
do
  echo "Try again"
done

or

while ! passwd
do
  echo "Try again"
done

Solution 2 - Bash

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.

Solution 3 - Bash

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.

Solution 4 - Bash

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

Solution 5 - Bash

You can use an infinite loop to achieve this:

while true
do
  read -p "Enter password" passwd
  case "$passwd" in
    <some good condition> ) break;;
  esac
done

Solution 6 - Bash

while [ -n $(passwd) ]; do
        echo "Try again";
done;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ VView Question on Stackoverflow
Solution 1 - BashErikView Answer on Stackoverflow
Solution 2 - BashMarc BView Answer on Stackoverflow
Solution 3 - BashduckworthdView Answer on Stackoverflow
Solution 4 - BashaclowkayView Answer on Stackoverflow
Solution 5 - BashkurumiView Answer on Stackoverflow
Solution 6 - BashAndrés RivasView Answer on Stackoverflow