View Single Post
  #1   (View Single Post)  
Old 31st December 2015
J65nko J65nko is offline
Administrator
 
Join Date: May 2008
Location: Budel - the Netherlands
Posts: 3,504
Default Comparing strings with the shell

From test(1):
Code:
 s1 = s2
    True if the strings s1 and s2 are identical.
s1 != s2
    True if the strings s1 and s2 are not identical.
s1 < s2
    True if string s1 comes before s2 based on the ASCII value of their characters.
s1 > s2
    True if string s1 comes after s2 based on the ASCII value of their characters.
So here we go .....
Code:
$ if [ 'aaa' < 'aab' ] ; then echo stringwise smaller ; fi
ksh: cannot open aab: No such file or directory
Ok the '<' in the shell means to take the contents of file 'aab' and use it as input. So we escape the '<' ...
Code:
$ if [ 'aaa' \< 'aab' ] ; then echo stringwise smaller ; fi
ksh: [: <: unexpected operator/operand
Yes, this is OpenBSD and the standard shell is ksh(1) .... Obviously the escaping does not work here.

Then I remember that shells have built-in's commands that sometimes behave differently than the ones residing in /bin/ for example. Checking the shell test command From ksh(1):
Code:
test expression
[ expression ]
        test evaluates the expression and returns zero status if true, 1
        if false, or greater than 1 if there was an error.  It is
        normally used as the condition command of if and while
        statements. 
[snip]
        -n string          string is not empty.

        -z string          string is empty.

        string = string    Strings are equal.

        string == string   Strings are equal.

        string != string   Strings are not equal

        number -eq number  Numbers compare equal.
Notice that the string comparison operators < and > are missing.
The /bin/test executable instead of the ksh one works with escaping the '<':
Code:
$ if  /bin/test "aap" \< "aap2" ; then echo Smaller! ; fi
Smaller!
If you forget to escape the shell output redirector ">" then ....
Code:
$ if  /bin/test "aap2" > "aap" ; then echo Larger! ; fi   
Larger!
$ if  /bin/test "aap" > "aap" ; then echo Larger! ; fi   
Larger!
$ ls -l aap
-rw-r--r--  1 adriaan  adriaan  0 Dec 31 02:05 aap
With an escape it works:
Code:
$  if  /bin/test "aap" \> "aap" ; then echo Larger! ; fi
$
Yes, this has cost me some headache to figure out .....
__________________
You don't need to be a genius to debug a pf.conf firewall ruleset, you just need the guts to run tcpdump
Reply With Quote