Linux if equals string

How do I compare two string variables in an ‘if’ statement in Bash? [duplicate]

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:

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

12 Answers 12

For string equality comparison, use:

For string does NOT equal comparison, use:

For the a contains b , use:

(and make sure to add spaces between the symbols):

The double equals sign is an error in the first case. Bash tolerates it, but the portable variant is if [ «$s1» = «$s2» ] . See also Rahul’s answer

@Sangimed, [ is a command (actually, an alternate name for the command called test ); if you run which [ , you’ll see there’s actually an executable file for it on disk (even though the shell may provide a built-in implementation as a performance optimization). Just like you have to put a space between the name of the command ls before the name of the file you want it to print, you need to put a space after the name of the [ command and its first argument, and between each argument it’s passed (if invoked as [ rather than test , it expects its last argument to be ] ).

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.

Many thanks for pointing out the necessary space. Solved my problem. Just started bash today, seems to be a lot of times spaces can cause an error, i.e declaring variables etc.

== doesn’t work on ash, dash, or other places baseline POSIX implementations of test . Use = instead.

Just wanted to say to make sure to leave a space between the beginning and ending square brackets and the «$s1» == «$s2» statement or it will not work. Also, this works too: if test «$s1» = «$s2»

== doesn’t work on ash, dash, or other places baseline POSIX implementations of test . Use = instead.

Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the ‘=’ sign.

Also, be careful of your script header. It’s not the same thing whether you use

Upvote, but always be careful when reading the ABS. Linking to a more authoritative source would probably be preferred.

@holms, that doesn’t happen with the OP’s code when used precisely as given here. You’ll need to show your exact usage.

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash IMO.

Читайте также:  Mediatek wireless driver linux

Here are some examples Bash 4+:

Example 1, check for ‘yes’ in string (case insensitive):

Example 2, check for ‘yes’ in string (case insensitive):

if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then 

Example 3, check for ‘yes’ in string (case sensitive):

Example 4, check for ‘yes’ in string (case sensitive):

Example 5, exact match (case sensitive):

Example 6, exact match (case insensitive):

This question has already great answers, but here it appears that there is a slight confusion between using single equal ( = ) and double equals ( == ) in

The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash in the starting of the script and save your script as filename.bash . To execute, use bash filename.bash — then you have to use == .

If you are using sh then use #!/bin/sh and save your script as filename.sh . To execute use sh filename.sh — then you have to use single = . Avoid intermixing them.

The assertion «you have to use == » is incorrect. Bash supports both = and == . Also, if you have #!/bin/bash at the start of your script, you can make it executable and run it like ./filename.bash (not that the file extension is important).

Perfect, I think I have to delete this answer now but it will be very helpful if you explain why this is not working without making the file executable and running by adding sh/bash before the filename?

This is confused about the significance of the shebang and the file name. If you have correctly put #!/bin/sh or #!/bin/bash as the first line of the script, you simply run it with ./filename and the actual file name can be completely arbitrary.

Now this is getting interesting,even if you don’t add any shebang and any extension and execute it using «bash/sh filename» it is working no matter what you use single equal or double equals.One more thing if you make the same file(without shebang and any extension) executable then you can execute it like ./filename (no matter of single or double equals).(Tried it on Arch linux with bash 4.3.46).

If you execute the file by running say «bash filename» — then you are just passing ‘filename’ as a parameter to the program ‘bash’ — which of course will result in bash running it. However if you set ‘filename’ execute permission, and try to run it by eg ‘./filename’ — then you are relying on the default ‘execute’ behaviour of your current command shell — which probably requires the «#!(shell)» line at the start of the script, in order to work.

#!/bin/bash s1="hi" s2="hi" if [ $s1 = $s2 ] then echo match fi 

Without the double quotes and with only one equals.

Why would you omit the double quotes? They are optional but harmless in this limited specific case, but removing them would be a serious bug in many real-world situations. See also stackoverflow.com/questions/10067266/…

I got same behavior with = or == regardless of quotes. I’m not sure if this is shell specific, I am using zsh on my mac OS version : 10.15.7 (19H15)

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

The double equals sign is tolerated in Bash, but not in some other dialects. For portability, the single equals sign should be preferred, and if you target Bash only, the double brackets [[ extension would be superior for versatility, robustness, and convenience.

Читайте также:  Double commander linux plugin

I don’t have access to a Linux box right now, but [ is actually a program (and a Bash builtin), so I think you have to put a space between [ and the first parameter.

Also note that the string equality operator seems to be a single = .

The symbol [ was a link to /bin/test at one time (or perhaps vice versa). That is apparently no longer the case on ubuntu 16.04; no idea where or when the change occurred.

I believe Prisoner 13 was incorrect. ‘[‘ is equivalent to ‘test’ in Ubuntu v20, with the requirement that the last argument must be ‘]’.

This is more a clarification than an answer! Yes, the clue is in the error message:

which shows you that your «hi» has been concatenated to the «[«.

Unlike in more traditional programming languages, in Bash, «[» is a command just like the more obvious «ls», etc. — it’s not treated specially just because it’s a symbol, hence the «[» and the (substituted) «$s1» which are immediately next to each other in your question, are joined (as is correct for Bash), and it then tries to find a command in that position: [hi — which is unknown to Bash.

In C and some other languages, the «[» would be seen as a different «character class» and would be disjoint from the following «hi».

Hence you require a space after the opening «[«.

Источник

Bash Compare Strings – Learn about Equals, Not Equals, Greater than and Less than!

bash compare strings

Dealing with strings is part of any programming language. When working with Bash scripts you will need to compare the value of two strings to determine whether they are equal or not.

String comparison is very useful and one of the most used statements in Bash scripts and its crucial to understand and know how to use it.

In this tutorial we will show you different use cases for string comparison in Bash Linux.

Basic Syntax of String Comparison

Basic syntax of string comparison is shown below:

if [ conditions/comparisons]
then
commands
fi

Check If Two Strings are Equal or Not Equal

In this section, we will learn how to check if two strings are equal or not equal in Bash script.

Check If Two Strings are Equal

You can use equal operators = and == to check if two strings are equal. You must use single space before and after the == and = operators.

In this example, we will use (=) operator with if statement to check if the strings are equal or not and returns the output.

First, create a test.sh script as shown below:

#!/bin/bash
str1=»Linux»;
str2=»Linux»;
if [ $str1 = $str2 ]
then
echo «Strings are same»;
else
echo «Strings are not same»;
fi

Save and close the file when you are finished. Then, run this script with the following command:

You should see the following output:

You can also use the following bash script to take input from the user and check if given strings are equal or not.

First, create a new test.sh file as shown below:

#!/bin/bash
read -p «Enter Your First String: » str1
read -p «Enter Your Second String: » str2
if [ $str1 = $str2 ]
then
echo «Strings are same»;
else
echo «Strings are not same»;
fi

Save and close the file when you are finished. Then, run the script as shown below:

Читайте также:  Astra linux dev установка

You will be asked to enter first and second string as shown below:

Enter Your First String: Linux
Enter Your Second String: Ubuntu
Strings are not same

== Operator to Compare Strings

You can also use (==) operator to compare two strings. Let’s see another example:

#!/bin/bash
str1=»Hitesh»;
str2=»Rajesh»;
if [[ $str1 == $str2 ]]
then
echo «Strings are same»;
else
echo «Strings are not same»;
fi

Save and close the file when you are finished. Then, run this script with the following command:

You should see the following output:

Check If Two Strings are Not Equal (!=)

Bash also provides the negation operator to use “if not equal” condition in bash scripts. You can use (!=) operator to check when both strings are not equal.

Let’s create a new test.sh script as shown below:

#!/bin/bash
str1=»Linux»
str2=»Windows»
if [ «$str1» != «$str2» ]
then
echo «Not Equal Strings»
else
echo «Equal Strings»
fi

Save and close the file when you are finished. Then, run this script with the following command:

You should see the following output:

Check If String is Empty

Bash also allows you to check whether the string is empty.

First, create another test.sh script to check that the string is empty.

#!/bin/bash
str1=»»
if [ -z $str1 ]
then
echo «String is empty»
else
echo «String is not empty»
fi

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

Next, create an another test.sh script to check that the string is not empty.

#!/bin/bash
str1=»Linux»
if [ -z $str1 ]
then
echo «String is empty»
else
echo «String is not empty»
fi

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

Check If First String is Greater Than or Less Than Second String (\>) or (\<)

First, create a test.sh script to check if the first string is greater than the second string.

#!/bin/bash
str1=»Webservertalk»
str2=»Webserver»
if [ $str1 \> $str2 ]
then
echo «$str1 is greater then $str2»
else
echo «$str1 is not greater then $str2»
fi

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

Webservertalk is greater then Webserver

Next, create a test.sh script to check if the first string is less than the second string.

#!/bin/bash
str1=»welcome»
str2=»welcometowebserver»
if [ $str1 \ < $str2 ]
then
echo «$str1 is less then $str2»
else
echo «$str1 is not less then $str2»
fi

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

welcome is less then welcometowebserver

Conclusion

In the above tutorial, we learned how to compare two strings in bash scripts. We hope you have learned how to compare two strings in bash. Feel free to leave comments below if you have any questions.

Recent Posts

  • Forcepoint Next-Gen Firewall Review & Alternatives
  • 7 Best JMX Monitoring Tools
  • Best PostgreSQL Backup Tools
  • Best CSPM Tools
  • Best Cloud Workload Security Platforms
  • Best Automated Browser Testing Tools
  • Event Log Forwarding Guide
  • Best LogMeIn Alternatives
  • Citrix ShareFile Alternatives
  • SQL Server Security Basics
  • Cloud Security Posture Management Guide
  • Cloud Workload Security Guide
  • The Best JBoss Monitoring Tools
  • ITL Guide And Tools
  • 10 Best Enterprise Password Management Solutions

Источник

Оцените статью
Adblock
detector