problem in string comparison in shell programming

Hello,
was just wondering how to compare strings in unix? I mean as in C there is a function strcmp() in string.h, is there any function in unix for that? I tried using

    if [ "p" > "q" ]

and all such variations but didn't succeed. Any help would be appreciated. Thanks in advance :slight_smile:

Hi,

you can compare string..like below..

if [ $valuea -ge $valueb ]
then
command
else
command
fi

to compare two strings..

you can use lessthan --> -le
greater than -ge
equal -eq

Thanks
Sha

hi
you can compare the string by the following commands as u have told strcmp() in C
if [ "$string1" == "$string2" ]
then

else

fi

In bash, you can compare alphabetically, but it is not standard. You need to escape the angle bracket:

if [ p \> q ]

I dont think you can compare strings with -le -gt -ge. It's meant for only integer comparison.

cfajohnson :slight_smile: You're the man. Thanks!!

Just a quick note - the string comparison is based on the ASCII value of the characters in the string and may fail for strings containing non-ASCII characters.

It should work for any values. It compares "lexicographically in the current locale".

Not necessarily true. It will result in an unsatisfactory ordering for certain locales unless the correct collator (for the locale) is provided in the underlying OS to allow locale-sensitive ordering. Bash and other shells do not include built-in collators.

Some shells such as ksh93 and zsh specifically avoid the issue for this reason. From the ksh93 man page

The zsh manual has almost identical text.

The bash manual states, "lexicographically in the current locale", but in fact uses the character's ASCII value.

The shell does use the locale's collating order for character ranges, e.g., [a-z]. I don't know whether the order is generated by the shell or by the OS.