Wednesday, July 27, 2011

The test command


The test command, [ ], and [[ ]]
When writing a shell script or programming in any modern language, the ability to evaluate expressions or values is essential to competent programs. UNIX has it covered as always with the test command. As the test man page states, the testcommand evaluates expression parameters and, if the expression value is True, returns a zero (True) exit value. For more information on the definition of test and all the available conditions, see the test man page.
To use the test command, simply provide the command with the appropriate flag and file name. When test has evaluated the expression, you're returned to a command prompt, where you can verify the return code, as shown in Listing 10.

Listing 10. Verify return code
# ls รข€“l
-rwxr-xr-x    1 cormany  atc             786 Feb 22 16:11 check_file
-rw-r--r--    1 cormany  atc               0 Aug 04 20:57 emptyfile

# test -f emptyfile
# echo $?
0

# test -f badfilename
# echo $?
1

As stated in the definition, test returns a zero exit value if the expression value was True or a non-zero exit value (that is, 1). InListing 10, the file emptyfile was found, so test returned 0; the file badfilename was not found, so 1 was returned.
Another way to use the test command is to place the expression to evaluate within single brackets ([ ]). Using the testcommand or replacing it with [ ] returns the same value, as they are identical executions:
# [ -f emptyfile ]
# echo $?
0

# [ -f badfilename ]
# echo $?
1

Using single brackets ([ ]) versus double brackets ([[ ]]) is a personal preference and really depends on how you've been taught commands and shell scripting. But keep in mind that there are some differences between the two evaluations. Although [ ] and [[ ]] use the same test operators during evaluation, they use different logical operators.

No comments:

Post a Comment