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. function strcmp
  2. {
  3. local s1="$1"
  4. local s2="$2"
  5. if [ "$s1" = "$s2" ] ; then
  6. return 0
  7. fi
  8. r=$(echo -e -n "$s1n$s2"|sort|head -n 1)
  9. if [ "$r" = "$s1" ] ; then
  10. return -1
  11. fi
  12. if [ "$r" = "$s2" ] ; then
  13. return 1
  14. fi
  15. }

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.  
  2. function strcmp
  3. {
  4. if [ "$1" = "$2" ] ; then
  5. return 0
  6. fi
  7. if [ "$1" '>' "$2" ] ; then
  8. return 1
  9. fi
  10. return -1
  11. }

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.  
  2. function strcmp
  3. {
  4. if [ "$1" = "$2" ] ; then
  5. return 0
  6. fi
  7. if expr "$1" ">" "$2" ; then
  8. return 1
  9. fi
  10. return -1
  11. }
  12.  

Leave a Reply