strcmp in bash

If you want to compare two strings in shell you can use something like

test "$str1" = "$str2" but that will only tell you if the strings are equal. The strcmp(3) C function also tells you if the first string is less or greater then the second ( alphabetically) . I created a similar function in shell.


My function takes two arguments and compares them alphabetically. My idea was to put the strings in a list, sort the list and then verify which string is the first in the list.

This function returns 0 if the strings are equal, -1 (actually 255 because you can't return a negative value from a function) if the first string is less then the second and 1 if the second argument is greater then the first.

  1. span style="color: #ff0000;">"$1""$2""$s1" = "$s2""$s1n$s2""$r" = "$s1""$r" = "$s2"

Update:
The built in test for bash 3.x supports string ">" and "<" for strings :

STRING1 < STRING2
True if STRING1 sorts before STRING2 lexicographically.
STRING1 > STRING2
True if STRING1 sorts after STRING2 lexicographically.

so we can rewrite the function like this :

  1. span style="color: #ff0000;">"$1" = "$2""$1" '>' "$2"

So if you have bash 3.x use the new function because it's faster

Update 2:
you can also do it using expr like this :

  1. span style="color: #ff0000;">"$1" = "$2""$1" ">" "$2"

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.