UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 46.4 Stop Syntax Errors in Numeric Tests Chapter 46
Shell Script Debugging and Gotchas
Next: 46.6 Watch Out for Bourne Shell -e Bug
 

46.5 Stop Syntax Errors in String Tests

Using the test or [ (square bracket) command (44.20) for a string test can cause errors if the variable starts with a dash (-). For example:

if [ "$var" = something ]
then ...

If $var starts with -r, the test command may think that you want to test for a readable file.

One common fix (that doesn't always work; see below) is to put an extra character at the start of each side of the test. This means the first argument will never start with a dash; it won't look like an option:

if [ "X$var" = Xsomething ]
then ...

That trick doesn't work if you want the test to fail when the variable is empty or not set. Here's a test that handles empty variables:

case "${var+X}" in
X) ...do this if variable is set...
   ;;

*) ...do this if variable is not set...
   ;;
esac

If $var is set (even if it has an empty string), the shell replaces ${var+X} (45.12) with just X and the first part of the case succeeds. Otherwise the default case, *), is used.

- JP


Previous: 46.4 Stop Syntax Errors in Numeric Tests UNIX Power ToolsNext: 46.6 Watch Out for Bourne Shell -e Bug
46.4 Stop Syntax Errors in Numeric Tests Book Index46.6 Watch Out for Bourne Shell -e Bug

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