Executing Code Based on Test Results

All programming languages have some way of deciding whether to execute code based on whether a condition is true or not. The shell provides this to you as the if statement. A small if statement has the general syntax shown on the right, next to a code example on the left:

if [ "$CNT" -eq 25 ]            #    if condition
then                            #    then
    cp acme /tmp/archive        #       command(s)
    rm /tmp/acme                #
fi                              #    fi

The full possible general syntax of the if statement is shown on the left, with example code on the right:

if [ "$CNT" -eq 25 ] # if condition 1 then # then cp acme /tmp/archive # command(s) rm /tmp/acme # elif [ "$CNT" -gt 25 ] # elif condition 2 then # then cp acme2 /tmp/archive # command(s) elif [ "$CNT" -gt 0 ] # elif condition 3 then ...

Get Practical UNIX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.