UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 46.3 Bourne Shell Debugger Shows a Shell Variable Chapter 46
Shell Script Debugging and Gotchas
Next: 46.5 Stop Syntax Errors in String Tests
 

46.4 Stop Syntax Errors in Numeric Tests

The test and [ (square bracket) commands (44.20) can compare two numbers. But it's an error if one of the numbers you test is stored in a shell variable that's empty or doesn't exist. For example, an empty num variable here will give you a Syntax error:

if [ "$num" -gt 0 ]
then ...

To stop syntax errors, add a leading zero, like this:

if [ "0$num" -gt 0 ]
then ...

In that case, if $num is empty, the test will compare 0 to 0. If $num is 1, the test will be true (because 01 is greater than 0)-and so on, just as it should be.

- JP


Previous: 46.3 Bourne Shell Debugger Shows a Shell Variable UNIX Power ToolsNext: 46.5 Stop Syntax Errors in String Tests
46.3 Bourne Shell Debugger Shows a Shell Variable Book Index46.5 Stop Syntax Errors in String Tests

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