| 1 | #!/bin/bash |
| 2 | # str-test.sh: Testing null strings and unquoted strings, |
| 3 | #+ but not strings and sealing wax, not to mention cabbages and kings . . . |
| 4 | |
| 5 | # Using if [ ... ] |
| 6 | |
| 7 | # If a string has not been initialized, it has no defined value. |
| 8 | # This state is called "null" (not the same as zero!). |
| 9 | |
| 10 | if [ -n $string1 ] # string1 has not been declared or initialized. |
| 11 | then |
| 12 | echo "String \"string1\" is not null." |
| 13 | else |
| 14 | echo "String \"string1\" is null." |
| 15 | fi # Wrong result. |
| 16 | # Shows $string1 as not null, although it was not initialized. |
| 17 | |
| 18 | echo |
| 19 | |
| 20 | # Let's try it again. |
| 21 | |
| 22 | if [ -n "$string1" ] # This time, $string1 is quoted. |
| 23 | then |
| 24 | echo "String \"string1\" is not null." |
| 25 | else |
| 26 | echo "String \"string1\" is null." |
| 27 | fi # Quote strings within test brackets! |
| 28 | |
| 29 | echo |
| 30 | |
| 31 | if [ $string1 ] # This time, $string1 stands naked. |
| 32 | then |
| 33 | echo "String \"string1\" is not null." |
| 34 | else |
| 35 | echo "String \"string1\" is null." |
| 36 | fi # This works fine. |
| 37 | # The [ ... ] test operator alone detects whether the string is null. |
| 38 | # However it is good practice to quote it (if [ "$string1" ]). |
| 39 | # |
| 40 | # As Stephane Chazelas points out, |
| 41 | # if [ $string1 ] has one argument, "]" |
| 42 | # if [ "$string1" ] has two arguments, the empty "$string1" and "]" |
| 43 | |
| 44 | |
| 45 | echo |
| 46 | |
| 47 | |
| 48 | string1=initialized |
| 49 | |
| 50 | if [ $string1 ] # Again, $string1 stands unquoted. |
| 51 | then |
| 52 | echo "String \"string1\" is not null." |
| 53 | else |
| 54 | echo "String \"string1\" is null." |
| 55 | fi # Again, gives correct result. |
| 56 | # Still, it is better to quote it ("$string1"), because . . . |
| 57 | |
| 58 | |
| 59 | string1="a = b" |
| 60 | |
| 61 | if [ $string1 ] # Again, $string1 stands unquoted. |
| 62 | then |
| 63 | echo "String \"string1\" is not null." |
| 64 | else |
| 65 | echo "String \"string1\" is null." |
| 66 | fi # Not quoting "$string1" now gives wrong result! |
| 67 | |
| 68 | exit 0 # Thank you, also, Florian Wisser, for the "heads-up". |