bash, dash and string comparison

LiraNuna picture LiraNuna · Jul 7, 2009 · Viewed 36.1k times · Source

I am trying to compare two strings in a simple shell script. I was using /bin/sh instead of /bin/bash, and after countless hours of debugging, it turns out sh (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 using /bin/sh? I know I can always do the opposite by using !=, but I am wondering about a cleaner, portable way.

Answer

J-16 SDiZ picture J-16 SDiZ · Jul 7, 2009

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
    some_command
fi