strcmp in bash


Thanks for visiting! If you're new here, you may want to subscribe to my RSS feed. This blog posts regular information about web development, unix/linux, How-tos and patches. Go ahead, subscribe to my feed! You can also receive updates via email, instant messenger, skype or tweeter.

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.

function strcmp
{
local s1="$1"
local s2="$2"
if [ "$s1" = "$s2" ] ; then
        return 0
fi
r=$(echo -e -n "$s1n$s2"|sort|head -n 1)
if [ "$r" = "$s1" ] ; then
        return -1
fi
if [ "$r" = "$s2" ] ; then
        return 1
fi
}

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 :

 
function strcmp
{
if [ "$1" = "$2" ] ; then
return 0
fi
if [ "$1" '>' "$2" ] ; then
return 1
fi
return -1
}

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 :

 
function strcmp
{
if [ "$1" = "$2" ] ; then
return 0
fi
if expr "$1" ">" "$2" ; then
return 1
fi
return -1
}
 
  • Digg
  • Reddit
  • del.icio.us
  • Slashdot
  • Spurl
  • StumbleUpon
  • Furl
  • description
  • Netscape
  • NewsVine
  • Technorati
  • YahooMyWeb
  • Simpy
If you enjoyed this post, you should subscribe to my full RSS Feeds

close Reblog this comment
blog comments powered by Disqus

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License

Technology Blogs - Blog Top Sites Search For Blogs, Submit Blogs, The Ultimate Blog Directory Blogarama - The Blog Directory 5starsblog Computers Blogs - Blog Flare blog search directory gob BlogHop