Stop Syntax Errors in String Tests (Unix Power Tools, 3rd Edition)
37.4. Stop Syntax Errors in String Tests
Using
the test or [
(square bracket) command (Section 35.26)
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
Bourne shell 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} (Section 36.7) with just X and the first
part of the case succeeds. Otherwise the default
case, *), is used.
See also Section 37.3 for a brief example of
bash parameter expansion and dealing with unset or
null values by reporting an error or by assigning default values.
-- JP
37.3. Stop Syntax Errors in Numeric Tests37.5. Quoting and Command-Line Parameters
Copyright © 2003 O'Reilly & Associates. All rights reserved.
Wyszukiwarka
Podobne podstrony:
ch37ch37 (3)ch37ch37ch37 (5)ch37ch37ch37CH37ch37 (2)Ch37ch37ch37ch37ch37CH37 (4)więcej podobnych podstron