UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.19 The Bourne Shell set Command Chapter 44
Shell Programming for the Uninitiated
Next: 44.21 Picking a Name for a New Command
 

44.20 test: Testing Files and Strings

UNIX has a command called test that does a lot of useful tests. For instance, test can check whether a file is writable before your script tries to write to it. It can treat the string in a shell variable as a number and do comparisons ("is that number less than 1000?"). You can combine tests, too ("if the file exists and it's readable and the message number is more than 500..."). Some versions of test have more tests than others. For a complete list, read your shell's manual page (if your shell has test built in (1.10)) or the online test(1) manual page.

The test command returns a zero status (44.7) if the test was true or a non-zero status otherwise. So people usually use test with if, while, or until. Here's a way your program could check to see if the user has a readable file named .signature in the home directory:

$HOME 



$myname 

if test -r $HOME/.signature
then
    ...Do whatever...
else
    echo 
    exit 1
fi

The test command also lets you test for something that isn't true. Add an exclamation point (!) before the condition you're testing. For example, the following test is true if the .signature file is not readable:

if test ! -r $HOME/.signature
then
    echo "$myname: Can't read your '.signature'.  Quitting." 1>&2
    exit 1
fi

UNIX also has a version of test (a link to the same program, actually) named [. Yes, that's a left bracket. You can use it interchangeably with the test command with one exception: there has to be a matching right bracket (]) at the end of the test. The second example above could be rewritten this way:

if [ ! -r $HOME/.signature ]
then
    echo "$myname: Can't read your '.signature'.  Quitting." 1>&2
    exit 1
fi

test
Be sure to leave space between the brackets and other text. There are a couple of other common gotchas caused by empty arguments; articles 46.4 and 46.5 have workarounds. (For completeness, GNU test is on the CD-ROM. But, for speed, we recommend using your shell's built-in version unless you need one of the GNU features.)

- JP


Previous: 44.19 The Bourne Shell set Command UNIX Power ToolsNext: 44.21 Picking a Name for a New Command
44.19 The Bourne Shell set Command Book Index44.21 Picking a Name for a New Command

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System