Conditionals

The Bourne shell has special constructs for conditionals, such as if/then/else and case statements. Here is a simple script with an if conditional that checks to see if the script's first argument is hi:

#!/bin/sh
if [ $1 = hi ]; then
   echo 'The first argument was "hi"'
else
   echo -n 'The first argument was not "hi" -- '
   echo It was '"'$1'"'
fi

The words if, then, else, and fi in the preceding script are shell keywords. Everything else is a command. This is an extremely important point, because one of the commands is [ $1 = "hi" ]. The [ character is an actual program on a Unix system; it is not special shell syntax. All Unix systems have a command called [ that performs tests for shell script conditionals. This program is also known ...

Get How Linux Works 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.