Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash, dash and string comparison

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.

like image 897
LiraNuna Avatar asked Jul 07 '09 00:07

LiraNuna


People also ask

Is Dash compatible with bash?

Dash is not Bash compatible, but Bash tries to be mostly compatible with POSIX, and thus Dash. Dash shines in: Speed of execution. Roughly 4x times faster than Bash and others.

What is == in bash script?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

How do you check if a line contains a string in bash?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.


1 Answers

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 
like image 97
J-16 SDiZ Avatar answered Oct 02 '22 03:10

J-16 SDiZ