views:

1136

answers:

4

While writing a fairly simple shell script, I've tried to compare two strings. I was using /bin/sh instead of /bin/bash, and after countless hours of debugging, it turns out dash (which is actually dash) can't handle this block of code:

if [ "$var" == "string" ]
then
    do something
fi

What is a portable way to compare strings uding /bin/sh? I know I can always do the opposite by using !=, but I am wondering about a cleaner, portable way.

+5  A: 

Why is there even a possibility that your script will be run by the "wrong" shell? I would think you could make that a pre-requisite of your product by using the standard sh-bang line at the top of your script:

#!/bin/bash

Even if a user uses a different shell, the other shells are generally still there and, if not, simply complain and state that they are a pre-req.

Exactly the same way that a specific kernel level, or the existence of awk, can be a pre-req.

For your specific question, I believe both sh and bash allow the single '=' to be used for string comparisons - that is POSIX behavior:

if [ "a" = "a" ] ; then
    echo yes
fi

yes
paxdiablo
+1  A: 

Use = instead of ==. Comparisons are handled by test(1). /usr/bin/[ is typically a link to /usr/bin/test . The only difference is that if youb use [ in a shell script, the ] is required aswell.

Note that bash has a built-in test/[, so it doesn't actually use /usr/bin/test.

skoob
+1  A: 

dash is a very strict POSIX shell, if it work in dash it is almost certain it would work in other POSIX shell.

Try:

if [ "$var" = "string" ]
then
    do something
fi
J-16 SDiZ
A: 

you can use awk

awk 'BEGIN{
 string1="test"
 string2="tes1t"
 if(s1==s2){
    print "same string"
 }else{
    print "not same"
 }
}'
ghostdog74