// Internet Duct Tape

Improve Your Scripting with the test Command

Posted in Links, Linux and Unix, Programming and Software Development, Technology by engtech on May 28, 2006

'test' is easily the most important command to know how to use when writing shell scripts. This is a really good tutorial that gives a full list of all supported commands and various Bourne shell examples.

The shortest-possible definition of the test command is that it appraises an expression and, if its condition is true, returns a 0 value. If the expression is not true, it returns a value greater than 0—which can also be said to be a false value. The easiest method of checking the status of the last command performed is via the $? value, and examples throughout this article use that parameter for purposes of illustration.The test command expects to find an argument on its command line, and when the shell has no value for a variable, the variable is considered null. This means that if a script is being processed, test reports the error whenever the script looks for an argument and does not find one.

When attempting to bulletproof scripts, you can solve this problem by enclosing all arguments within double quotes. The shell then expands the variables and, if no value exists, passes a null value to test. Another option is to add an extra check procedure within the script to see if the command-line arguments have been set. If not, the script can tell users that arguments are needed and then exit. All of this will make more sense as we work through some examples.

Improve Your Scripting with the test Command

Comments Off on Improve Your Scripting with the test Command

%d bloggers like this: