I'm trying to get an if statement to work in Bash (using Ubuntu):
#!/bin/bash  s1="hi" s2="hi"  if ["$s1" == "$s2"] then   echo match fi   I've tried various forms of the if statement, using [["$s1" == "$s2"]], with and without quotes, using =, == and -eq, but I still get the following error:
[hi: command not found
I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?
Eventually, I want to say if $s1 contains $s2, so how can I do that?
I did just work out the spaces bit... :/ How do I say contains?
I tried
if [[ "$s1" == "*$s2*" ]]   but it didn't work.
Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.
You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings.
In shell scripting, = and == are for string comparisons and -eq is for numeric ones. So, when comparing the strings, use = or == (depending on which shell you are using, sh or bash ), while to check for equality between integers, use -eq comparison operator.
For string equality comparison, use:
if [[ "$s1" == "$s2" ]]   For string does NOT equal comparison, use:
if [[ "$s1" != "$s2" ]]   For the a contains b, use:
if [[ $s1 == *"$s2"* ]]   (and make sure to add spaces between the symbols):
Bad:
if [["$s1" == "$s2"]]   Good:
if [[ "$s1" == "$s2" ]] 
                        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