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.
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.
== 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.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With