The while/until structure

while/until are looping structures.

  • while - while command returns success, execute the loops action body.
  • until - until command returns success, execute the loops action body.
  • Like if, while/until tests the exit status of specified command. Loop structure
  • while or until - keyword.
  • cmd - a command or command sequence. The exit status of command determine if loop body executed.
  • do - keyword, marks start of the action block (loop body).
  • action list - a sequence of commands to run. This may include other bash flow of control statement.
  • done - keyword marking the end of the action block. Special commands
  • break - used to break out of loop for reasons other than cmd's success. Usually listed as an action of an if statement.
  • continue - used to skip the rest of the action block and return to the top of the loop (re-run the test command).
    # prompts user for value 
    read -p "Input a number : " num
    
    # check that it is integer of 1 or more digits.
    # Until a good number given or q typed, keep asking.
    until echo "$num" | grep "^[0-9][0-9]*$" > /dev/null 2>&1
    do
      # if q entered, user Signaling quit.
      if [ "$num" = 'q' ]
      then
        break
      fi
    
      # ask again
      read -p "Bad number, Input a number : " num
    done
    
    #!/bin/bash
    
    function getnum ()
    {
      # Sets the variable num to an integer number
    
      # prompt user for a number
      read -p "Input a number : " num
    
      # check that it is only an integer
      # Until a good number given or q typed, keep asking.
      until echo "$num" | grep "^[0-9][0-9]*$" > /dev/null 2>&1
      do
        # if q entered, user Signaling quit.
        if [ "$num" = 'q' ]
        then
          return 1
          break
        fi
    
        # ask again
        echo "Bad number"
        read -p "Input a number : " num
      done
    }
    
    # Loop is endless and must be exited from by an
    #   internal action.
    while [ 1 = 1 ]
    do
    
      # get 1st input, if q, then exit program
      getnum
      num1=$num
      if [ "$num1" = 'q' ]
      then
        exit
      fi
    
      # get 2nd input, if q, then exit program
      getnum
      num2=$num
      if [ "$num2" = 'q' ]
      then
        exit
      fi
    
      # if either number > 1000, skip calculation and re-prompt
      if [ "$num1" -gt 1000 -o  "$num2" -gt 1000 ]
      then
        echo "User smaller values"
        continue
      fi
    
      # sum numbers and display
      total=$( expr $num1 + $num2 )
      echo "$num1 + $num2 = $total"
    
    done