1 #!/bin/bash 2 a=4 3 b=5 4 5 echo 6 if [ "$a" -ne "$b" ] 7 then 8 echo "$a is not equal to $b" 9 echo "(arithmetic comparison)" 10 fi 11 12 echo 13 14 if [ "$a" != "$b" ] 15 then 16 echo "$a is not equal to $b" 17 echo "(string comparison)" 18 fi 19 20 echo 21 22 exit 0
1 #!/bin/bash 2 # Testing null string and unquoted strings, but not strings 3 # and sealing wax, not to mention cabbages and kings... 4 5 # If a string has not been initialized, it has no defined value. 6 # This state is called `null`, not the same as zero! 7 8 if [ -n $string1 ] # string has not been declared or initialized. 9 then 10 echo "String \"string1\" is not null." 11 else 12 echo "String \"string1\" is null." 13 fi 14 15 # show $string1 is not null, although it was not initialized. 16 17 echo 18 19 # let's try it again 20 if [ -n "$string1" ] # this time, $string1 is quoted! 21 then 22 echo "String \"string1\" is not null." 23 else 24 echo "String \"string1\" is null." 25 fi # Quoted strings within test brackets! 26 27 echo 28 29 if [ $string1 ] # this time, $string1 stands naked. 30 then 31 echo "String \"string1\" is not null." 32 else 33 echo "String \"string1\" is null." 34 fi 35 36 # The [ ... ] test operator alone detects whether the string is null. 37 # However it is good practice to quote it like if [ "$string1" ] 38 # if [ $string1 ] has one arguments, "]" 39 # if [ "$string1" ] has two arguments, the empty "$string1" and "]" 40 41 echo 42 43 string1=initialized 44 if [ $string1 ] 45 then 46 echo "String \"string1\" is not null." 47 else 48 echo "String \"string1\" is null." 49 fi # Still, it is better to quote it as "$string1" 50 51 string1="a = b" 52 if [ $string1 ] 53 then 54 echo "String \"string1\" is not null." 55 else 56 echo "String \"string1\" is null." 57 fi 58 59 exit 0