Debian Codegraph @

str-test.sh

raw symbols SCIP
1 #!/bin/bashscip-shell filesystem . . `/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 [scip-shell system . . `[`. -n $string1 ] # string1 has not been declared or initialized.
11 then
12 echoscip-shell system . . echo. "String \"string1\" is not null."
13 else
14 echoscip-shell system . . echo. "String \"string1\" is null."
15 fi # Wrong result.
16 # Shows $string1 as not null, although it was not initialized.
17
18 echoscip-shell system . . echo.
19
20 # Let's try it again.
21
22 if [scip-shell system . . `[`. -n "$string1" ] # This time, $string1 is quoted.
23 then
24 echoscip-shell system . . echo. "String \"string1\" is not null."
25 else
26 echoscip-shell system . . echo. "String \"string1\" is null."
27 fi # Quote strings within test brackets!
28
29 echoscip-shell system . . echo.
30
31 if [scip-shell system . . `[`. $string1 ] # This time, $string1 stands naked.
32 then
33 echoscip-shell system . . echo. "String \"string1\" is not null."
34 else
35 echoscip-shell system . . 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 echoscip-shell system . . echo.
46
47
48 string1=initialized
49
50 if [scip-shell system . . `[`. $string1 ] # Again, $string1 stands unquoted.
51 then
52 echoscip-shell system . . echo. "String \"string1\" is not null."
53 else
54 echoscip-shell system . . 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 [scip-shell system . . `[`. $string1 ] # Again, $string1 stands unquoted.
62 then
63 echoscip-shell system . . echo. "String \"string1\" is not null."
64 else
65 echoscip-shell system . . 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".