LOOPIF        Test result code and conditionally branch using looping

Top  Previous  Next

Syntax:

LOOPIF

GOTO  [ label1 ]  else  GOTO  [ label2 ]

Arguments:

[ label1 ]

A valid label within the current script file which is branched to if the conditional test fails.

 

[ label2 ]

A valid label within the current script file which is branched to if the conditional test is successful.

Options:

none

 

 

 

This script command performs two or three-way branching based on the result code of the previous command and the current LOOPCOUNT value. This command is most commonly used in three-way mode to implement a "retry loop" that attempts a failed operation several times but eventually fails rather than looping indefinitely. An operation is considered to have failed when the %lasterror variable contains a non-zero value.

 

Three-way Branching

When LOOPCOUNT is set to a non-zero value, the LOOPIF command branches to [ label1 ] if the previous command failed or to [ label2 ] if the previous command succeeded. However, when the number of failures matches the value of LOOPCOUNT, neither branch is taken and control passes through to the command immediately after the LOOPIF command. This type of automatic retry loop is especially desirable in command scripts that depend on access to external network resources.

 

Consider the following where the DIALNET command is repeated up to three times or until it is successful. An email is sent if DIALNET fails three times.

 

LOOPCOUNT 3

:retry_dial

DIALNET "My Connection"

LOOPIF GOTO retry_dial ELSE GOTO connected

;; dialing failed three times

SET email_body = "Unable to establish dialup connection."

CREATEMAIL "Robo-FTP" "[email protected]" "Upload failed" email_body ""

SENDMAIL "smtp.mydomain.com" "" "[email protected]"

EXIT

:connected

FTPLOGON "ftp.acme-widget.com" /user=anonymous /pw=itchy

SENDFILE "*"

FTPLOGOFF

DISCONNECT

EXIT

 

Two-way Branching

When LOOPCOUNT is unassigned or explicitly set to zero the LOOPIF command branches to [ label1 ] if the previous command failed or to [ label2 ] if the previous command succeeded. Unlike the three-way branching described above, the number of times the previous command failed does not alter this branching behavior.

 

Consider the following where the DIALNET command is repeated until it is successful:

 

LOOPCOUNT 0 ;; error expected

:retry_dial

DIALNET "My Connection"

LOOPIF GOTO retry_dial ELSE GOTO connected

:connected

 

The example above is functionally equivalent to more common implementation shown in the example below:

 

:retry_dial

DIALNET "My Connection"

IFERROR!= $ERROR_SUCCESS GOTO retry_dial

:connected

 

 

Related command(s): LOOPCOUNT, LOOPTO, GOTO, IFERROR

See also: Fault Tolerant Scripts