O'Reilly logo

Practical UNIX by Steve Moritsugu - DTR Business Systems

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required