MERIDIAN DATA SYSTEMS // SCRIPTING

conditionals

DOCUMENT TYPE: SYSTEM REFERENCE NODE: conditionals 68 DOCUMENTS
MDS://KNOWLEDGE/SCRIPTING/conditionals
CONDITIONALS
============

Use if to run one block when a test succeeds and an optional else block when
it does not. Finish each conditional with fi:

    if [ -f "$HOME/notes.txt" ]; then
        cat "$HOME/notes.txt"
    else
        echo "No notes file"
    fi

The words if, then, else, and fi are written on separate lines, except then
may follow the test on the if line as shown. Indentation is optional but makes
nested blocks easier to read.

FILE TESTS
----------
Put spaces inside the square brackets:

    if [ -e "$HOME/notes.txt" ]; then
        echo "The entry exists"
    fi

Supported file tests:
- -e path: an entry exists.
- -f path: the entry is a file.
- -d path: the entry is a directory.

Paths are resolved in the virtual filesystem. Quote paths that contain spaces.

STRING COMPARISONS
------------------
Compare two values with = or !=:

    if [ "$USER" = "root" ]; then
        echo "Current user is root"
    fi

    if [ "$LABEL" != "" ]; then
        echo "$LABEL"
    fi

Keep spaces around the brackets and comparison operator. Use quotes around
expanded values, especially when they may contain spaces or be empty.

COMMAND CONDITIONS
------------------
A supported virtual-shell command can also be the if condition. Its success
or failure selects the branch:

    if cat "$HOME/notes.txt"; then
        echo "Read completed"
    else
        echo "The file could not be read"
    fi

SUPPORTED SYNTAX
----------------
The scripting language supports if, optional else, and nested if blocks. It
does not support elif, loops, functions, pipelines, or command substitution.
Use only commands available to scripts; see help bash-scripting for limits
and help <command> for command syntax.