IF

Conditionally execute commands

IF

Run command lines only if a condition holds.

if <cond> ["<command>" … [else "<command>" …]]

  • Condition: one word, run as a command line. It is true if that line succeeds. A plain number succeeds when non-zero, so if 1 is true and if 0 is false. $?name expands to 1 or 0 and is the usual way to test whether a variable is defined. Leading ! negates the condition.

  • Combining: || after a condition tries another one; && between commands starts a new condition. Everything is evaluated strictly left to right, without precedence or grouping.

  • Commands: each argument is one complete command line; quote lines with more than one word. else starts the commands for a false condition. While the IFError option is on (the default, see set), the list stops at the first command that fails. The result of if is that of the last command run, or success if none ran.

Warning

expr reports its value as the command’s result, and only 0 counts as success. So if "expr 2 > 1" is false and if "expr 0" is true. To test for a non-zero value, write if !"expr …", as Broadcom’s own rc.soc does (OpenBCM sdk-6.5.27/rc: rc.soc, config.bcm, td3_sanity.soc, cmd_td3_tr514_lr.soc, tr51/tr517_bcm56870_a0.soc, bcm_diag_info.soc …).

Whether it is safe depends on the commands. See Scripting.

Hardware-validated

drivshell> if 1 "echo hello" "echo world"
hello
world

Hardware-validated

drivshell> local n 3
drivshell> if !"expr $n > 2" "echo n is greater than 2" else "echo n is at most 2"
n is greater than 2

Built-in help

Parameters: <condition> [<command> ... [else <command> ...]]
    Execute a list of command lines(s) only if <condition> is a
    non-zero integer or a successful sub-command-line.  Command lines
    of more than one word must be quoted, for example:
        if 1 "echo hello" "echo world"
    will display hello and world.  Simple left-to-right boolean
    operations are permitted, for example:
        if $?quickturn && !"bist arl" "echo BIST failed"
    Processing of multiple command lines ends when one of them fails
    unless IFError is set to FALSE (see help on set for more info).
    The return value from this command is the result of the last
    executed command.

Further reading

SDK-6.5.20 HSDK Getting Started Guide (GS-SDK6520-R), plus SDK-6.5.20/21/22 Release Notes (RN-SDK65xx-R), OpenBCM sdk-6.5.27/rc: rc.soc, config.bcm, td3_sanity.soc, cmd_td3_tr514_lr.soc, tr51/tr517_bcm56870_a0.soc, bcm_diag_info.soc …, BCM_SDK命令.