How to use until loop in Shell Scripts

The until Loop

The until loop is very similar to the while loop, except that the until loop executes as long as the command fails. After the command succeeds, the loop exits and execution of the script continues with the statement following the done statement. The syntax for the until loop is:

until control_command 
do
    statement1
    ...       
    statementN
done

The control_command can be any command that exits with a success or failure status. The statements can be any utility commands, user programs, shell scripts, or shell statements. If the control_command fails, the body of the loop (all the statements between do and done) execute, and the control_command executes again. As long as the control_command continues to fail, the body of the loop continues to execute. As soon as the control_command succeeds, the statement following the done statement executes; for example:

$ cat until.ksh 
#!/bin/ksh

# Script name: until.ksh

num=1

until (( num == 6 )) 
do
        print "The value of num is: $num"
        (( num = num + 1 ))
done
print "Done."

Here is the output of the script:

$ ./until.ksh  
The value of num is: 1 
The value of num is: 2 
The value of num is: 3 
The value of num is: 4 
The value of num is: 5 
Done.
Related Post