LDP/LDP/guide/docbook/abs-guide/str-test.sh

69 lines
1.8 KiB
Bash
Raw Permalink Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2003-11-03 16:25:16 +00:00
# str-test.sh: Testing null strings and unquoted strings,
#+ but not strings and sealing wax, not to mention cabbages and kings . . .
2001-07-10 14:25:50 +00:00
# Using if [ ... ]
# If a string has not been initialized, it has no defined value.
2008-07-20 23:16:47 +00:00
# This state is called "null" (not the same as zero!).
2001-07-10 14:25:50 +00:00
2008-07-20 23:16:47 +00:00
if [ -n $string1 ] # string1 has not been declared or initialized.
2001-07-10 14:25:50 +00:00
then
echo "String \"string1\" is not null."
else
echo "String \"string1\" is null."
2008-07-20 23:16:47 +00:00
fi # Wrong result.
2001-07-10 14:25:50 +00:00
# Shows $string1 as not null, although it was not initialized.
echo
2008-07-20 23:16:47 +00:00
# Let's try it again.
2001-07-10 14:25:50 +00:00
if [ -n "$string1" ] # This time, $string1 is quoted.
then
echo "String \"string1\" is not null."
else
echo "String \"string1\" is null."
2003-11-03 16:25:16 +00:00
fi # Quote strings within test brackets!
2001-07-10 14:25:50 +00:00
echo
2001-09-04 13:27:31 +00:00
if [ $string1 ] # This time, $string1 stands naked.
2001-07-10 14:25:50 +00:00
then
echo "String \"string1\" is not null."
else
echo "String \"string1\" is null."
2008-07-20 23:16:47 +00:00
fi # This works fine.
# The [ ... ] test operator alone detects whether the string is null.
# However it is good practice to quote it (if [ "$string1" ]).
2001-07-10 14:25:50 +00:00
#
# As Stephane Chazelas points out,
2003-11-03 16:25:16 +00:00
# if [ $string1 ] has one argument, "]"
# if [ "$string1" ] has two arguments, the empty "$string1" and "]"
2001-07-10 14:25:50 +00:00
echo
string1=initialized
2008-07-20 23:16:47 +00:00
if [ $string1 ] # Again, $string1 stands unquoted.
2001-07-10 14:25:50 +00:00
then
echo "String \"string1\" is not null."
else
echo "String \"string1\" is null."
2008-07-20 23:16:47 +00:00
fi # Again, gives correct result.
2003-11-03 16:25:16 +00:00
# Still, it is better to quote it ("$string1"), because . . .
2001-07-10 14:25:50 +00:00
string1="a = b"
2008-07-20 23:16:47 +00:00
if [ $string1 ] # Again, $string1 stands unquoted.
2001-07-10 14:25:50 +00:00
then
echo "String \"string1\" is not null."
else
echo "String \"string1\" is null."
2008-07-20 23:16:47 +00:00
fi # Not quoting "$string1" now gives wrong result!
2001-07-10 14:25:50 +00:00
2008-07-20 23:16:47 +00:00
exit 0 # Thank you, also, Florian Wisser, for the "heads-up".