How do I compare two string variables in an 'if' statement in Bash?

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.


For string 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 [ "$s1" == "$s2" ]

You should be careful to leave a space between the sign of '[' and double quotes where the variable contains this:

if [ "$s1" == "$s2" ]; then
#   ^     ^  ^     ^
   echo match
fi

The ^ s show the blank spaces you need to leave.

链接地址: http://www.djcxy.com/p/24142.html

上一篇: 将所有输出重定向到文件

下一篇: 如何比较Bash中'if'语句中的两个字符串变量?