Tag Archives: =

Fun with string comparisons in BASH/Bourne Shell. Unix/Linux/Mac OS X/Cygwin


Short form:
Compare two strings, in BASH shell script. “$?” is 0 (true) if they are equivalent:
$ t3=a; o3=a; test “$t3” = “$o3” ; echo $?
0

Capture the true/false (0/non-zero) result in a variable:
$ t3=a; o3=; test “$t3” != “$o3” ; z=`echo “$?”`; echo $z
0

Remember $? is updated after every operation, so capture its value DIRECTLY after the test!

Long form::
As used as I’m getting to the generally low quality of software help/tutorial/manuals, this one is really a new low.
Here on page 133, in chapter 5 of the Fourth Edition of Unix Shell Programming by Lowell Jay Arthur & Ted Burns, in table 5.7, states:

s1 = s2 True if strings s1 and s2 are identical

BALONEY!

babbott$ tF3=a; oF3=b; test tF3 = oF3 ; echo $?
1
babbott$ tF3=a; oF3=a; test tF3 = oF3 ; echo $?
1

What this “1” means is that “tF3” and “oF3” are DIFFERENT strings. The comparison fails, and the 1 indicates “false”. “true” is 0.

But I’m getting wise to this stuff, So I put dollar signs ahead of them to mark them for substitution and double quotes around them specifying only $, \ and ` (back quote or back tick or graves have special meanings, AND allowing the reference to be processed even if the variable doesn’t exist and has never bveen assigned a value: Anyway:

babbott$ tF3=a; oF3=a; test “$tF3” = “$oF3” ; echo $?
0
babbott$ tF3=a; oF3=b; test “$tF3” = “$oF3” ; echo $?
1

NICE! FINALLY. I’ve been trying for 2 1/2 working days to figure out how to do a string variable to string variable comparison.

The really slick thing, which is their justification, is that the double quotes protect the code from uninitialized variables:

babbott$ tF3=a; oF3=; test “$tF3” = “$oF3” ; echo $?
1
babbott$ tF3=a; oF3=a; test “$tF3” = “$oF3” ; echo $?
0
babbott$ tF3=a; oF3=a; test “$tF3” != “$oF3” ; echo $?
1
babbott$ tF3=a; oF3=; test “$tF3” != “$oF3” ; echo $?
0

Gee. Well at least I know what to expect for a while.

Oh yes, if you want that pass/fail value to use for something further, here’s the only way I”ve come up with so far- I HAVE to believe this is sillier than it needs to be, and I’ll improve it when I get smarter about this stuff. But it works, its bullet-proof and I don’t have to think about it for the moment:

babbott$ tF3=a; oF3=; test “$tF3” != “$oF3” ; z=`echo “$?”`; echo $z
0
babbott$ tF3=a; oF3=a; test “$tF3” != “$oF3” ; z=`echo “$?”`; echo $z
1

And if you wonder why I just don’t use a compound statement with -a and -o switches for AND and OR logic, its because I’m comparing four pairs of strings. If all the pairs match, then do “A” else “B” Pardon me if I don’t really want to present an 8 argument test with two levels of parenthesis, 4 equals operators for the string pairs and 3 -a operators for the booleans, to future maintainers.

Bill