How can you run a command in bash over until success

前端 未结 6 796
走了就别回头了
走了就别回头了 2020-11-28 19:10

I have a script and want to ask the user for some information, the script cannot continue until the user fills in this information. The following is my attempt at putting a

相关标签:
6条回答
  • 2020-11-28 19:26

    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.

    0 讨论(0)
  • 2020-11-28 19:27
    until passwd
    do
      echo "Try again"
    done
    

    or

    while ! passwd
    do
      echo "Try again"
    done
    
    0 讨论(0)
  • 2020-11-28 19:32

    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.

    0 讨论(0)
  • 2020-11-28 19:34

    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
    
    0 讨论(0)
  • 2020-11-28 19:41

    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
    
    0 讨论(0)
  • 2020-11-28 19:41
    while [ -n $(passwd) ]; do
            echo "Try again";
    done;
    
    0 讨论(0)
提交回复
热议问题