|
|
|
|
UGU: Unix Guru Universe - Unix Tip #4433- April 30, 2024
- Home : Help
: Today's Tip
Unix Tip #4433- April 30, 2024
TEST TROUBLES IF STRING IS EMPTY
(1) bad ex.
if [ `echo "$OPTARG" | sed '/^[0-9][0-9]*$/!d` = "" ]
(2) fixed ex.
if [ `echo "$OPTARG" | sed '/^[0-9][0-9]*$/ s//X/'`= "X" ]
(3) another fixed ex. (Bourne Shell, ksh)
if [ -n "`echo "$OPTARG" | sed '/^[0-9][0-9]*$/!d'`" ]
(1) This produces an easy
to overlook error. On
success and the lack of
double quotes on the left
side cause test to think
there is no parameter,
producing an error (1).
This is because the result
is an empty string without
quotes and test doesn't
know that it is dealing
with a string, no parameter
seen.
Adding a character to the
beginning of each string is
a trick to fix it (2). The
test command sees a string
and simply compares as normal,
passing over the pair of
initial and equal characters.
Another fix (3) is to surround
the empty/not empty string with
double quotes. Test will see
the empty string and things
work as normal. This (3) works
in Bourne Shell and ksh but NOT
in csh.
Simple ex.
$ foo=""
$ test -n $foo # fails
$ test -n `echo $foo` # fails
$ test -z `echo x$foo` # works, might throw off the logic
$ test -n "`echo $foo`" # works in sh & ksh
This tip generously supported by: bigoldbulldog@hotmail.com
NOTE: All tips provided are USE AT YOUR OWN RISK. Tips are submitted
by various unix admins around the globe. UGU suggest you read and
test each tip in a non-volitile environment before placing into
production.
LAST 5 TIPS
4432
- ANOTHER PROCESS FINDER
4431
- VI REVERSAL
4430
- BANNERS ON TELNET
4429
- MOUNTING CD'S ON HPUX
4428
- OUT PARAMETER FROM ORACLE
I want to
SUBSCRIBE
and get a UGU Tip everyday.
I want to
UNSUBSCRIBE
and NOT get a UGU Tip everyday.
If you have a UNIX TIP let us know, we just may use it:
(All tips become the property of the Unix Guru Universe)
|
|
|
Copyright 1994-2024 Unix Guru Universe |
|
|
|
|