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.
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 }If you enjoyed this post, you should subscribe to my full RSS Feeds













Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment