Stop Syntax Errors in Numeric Tests (Unix Power Tools, 3rd Edition)
37.3. Stop Syntax Errors in Numeric Tests
The test and [ (square bracket) commands
( Section 35.26) 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.
The zero trick doesn't work with
negative numbers, though, so if you
expect ever to need to deal with negative numbers, you may want to
look into other methods of checking to see if a variable has a value,
such as this method from the bash shell, which
displays an error if the variable is null or unset, or the following method, which
assigns a default value:
#!/bin/sh
...
# check $num first, fail with error
tmp=${num:?"num not set"}
# use a default
default=0
if [ ${num:-default} -gt 0 ]
then
...
--JP and SJC
37.2. Bourne Shell Debugger Shows a Shell Variable37.4. Stop Syntax Errors in String Tests
Copyright © 2003 O'Reilly & Associates. All rights reserved.
Wyszukiwarka
Podobne podstrony:
ch37ch37ch37 (3)ch37ch37ch37 (5)ch37ch37ch37CH37ch37 (2)Ch37ch37ch37ch37CH37 (4)więcej podobnych podstron