How to Compare Strings in Bash
We can compare strings using various comparison operators and check if a string contains a substring using regular expressions.
String comparison in Bash
String comparison means checking whether the given strings are identical or not. Two or more strings are identical if they are of the same length and contain the same sequence of characters.
We use various string comparison operators which return true or false depending on the condition. Some of the widely used string comparison operators can be listed below.
string1 = string2 |
The equality operator used with [ the command returns if both operands are equal true . |
string1 == string2 |
The equality operator [[ is used with the command and returns if both operands are equal true . |
string1 != string2 |
Inequality operator, returns if the two operands are not equal true . |
string1 =~ regex |
Regex operator and returns if string1 qualifies as extended .regex true |
string1 > string2 |
Greater than operator, if string1 greater than string2 , returns in lexical (alphabetical) ordertrue |
string1 < string2 |
Less than operator, if string1 less than string2 , returns in lexical (alphabetical) ordertrue |
-z string |
If string the length of is 0 , return true . |
-n string |
If string the length of is not 0 , return true . |
String1="Hello World!!"
String2="Hello World!!"
String3="Delft Stack"
if [ "$String1" = "$String2" ]; then
echo "String1 and String2 are equal."
else
echo "String1 and String2 are not equal."
fi
if [[ "$String1" == "$String2" ]]; then
echo "String1 and String2 are equal."
else
echo "String1 and String2 are not equal."
fi
if [[ "$String1" != "$String3" ]]; then
echo "String1 and String3 are not equal."
else
echo "String1 and String3 are equal."
fi
Output:
String1 and String2 are equal.
String1 and String2 are equal.
String1 and String3 are not equal.
Here, if we first compare and using =
the operator . Since and both have the same length, have the same sequence of characters, the comparison operator returns , so we get as the output of the first block in the program.String1
String2
String1
String2
true
String1 and String2 are equal.
if-else
Similarly, in the second program, we used ==
the operator to compare String1
and String2
. In this case, we need to use [[
for the comparison.
Finally, we compare and using !=
the operator .String1
String3
Lexical comparison in Bash
Lexical comparison is comparing strings based on alphabetical order. For lexical comparison, we use >
and <
operators.
name1="Kamal"
name2="Abinash"
if [[ "$name1" > "$name2" ]]; then
echo "${name1} is greater then ${name2}."
elif [[ "$name1" < "$name2" ]]; then
echo "${name2} is greater than ${name1}."
else
echo "Both the namees are equal"
fi
Output:
Kamal is greater then Abinash.
In this program, name1
and name2
are lexically compared. Since K
is alphabetically after A
and K
has a higher value than A
, it "$name1" > "$name2"
is returned true
and we get Kamal is greater then Abinash.
as output.
Check if a string is empty
We use the "-n" and "-z" operators to check if the string is empty.
String=""
if [[ -z $String ]]; then
echo "The variable String is an empty string."
fi
Output:
The variable String is an empty string.
In this program, string
is an empty variable. Since -z
the operator returns true
, if string
the length of is 0
, hence we get The variable String is an empty string.
as the output of the given program.
String="Test"
if [[ -n $String ]]; then
echo "The variable String is not an empty string."
fi
Output:
The variable String is not an empty string.
In this program, String
is a non-null variable. Since -n
the operator returns true
, if string
the length of is not 0
, therefore we get The variable String is not an empty string.
as the output of the given program.
Check if a string contains a substring
To check if a string contains a substring, we can use the =~
( Regex
) operator.
The operator returns if the string matches the expanded regex
expression . We must craft a suitable expression to do the comparison.regex
true
regex
String='My name is Delft.'
if [[ $String =~ .*Delft.* ]]; then
echo "The given string has Delft on it."
fi
Output:
The given string has Delft on it.
Here, .*Delft.*
is the expression to match regex
, which means match Delft.
any string before and after, 0 or more characters. It checks if there is a substring in the string Delft
.
Since Delft
exists in the given string, the given condition is satisfied and we get The given string has Delft on it.
as the output.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Formatting a number as a dollar amount in PHP
Publish Date:2025/04/13 Views:75 Category:PHP
-
This article will cover different ways to format numbers as dollar amounts in PHP with examples. These include: number_format NumberFormatter::formatCurrency Regular expressions Manual format We'll also look at why money_format the function
Pandas Convert String to Number
Publish Date:2025/04/12 Views:147 Category:Python
-
This tutorial explains how to pandas.to_numeric() convert string values of a Pandas DataFrame into numeric type using the method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 , 103 , 343 , 565 ], "Name" :
Split a string into two lists using str.split in Python Pandas
Publish Date:2025/04/12 Views:139 Category:Python
-
Pandas has a method to split a string based on a separator/delimiter. We will use the pandas str.split() function. str.split() Split a string into two lists/columns using the function in Python Pandas The string can be saved as a list of Se
Joining columns using Select in PostgreSQL
Publish Date:2025/04/11 Views:176 Category:PostgreSQL
-
MySQL PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitors . Today we will learn how to use SELECT the operator to join the columns of a table. Using operators to || joi
PostgreSQL replace string
Publish Date:2025/04/11 Views:91 Category:PostgreSQL
-
This article discusses how to use PostgreSQL replace() functions to replace strings. Use the PostgreSQL replace() function to replace strings PostgreSQL replace() functions have the following arguments, which are all text types: replace (st
Searching for occurrences of a string in a MySQL database
Publish Date:2025/04/11 Views:200 Category:MySQL
-
As a database administrator, there are certain situations and circumstances where you have to search the entire database for the occurrence of a pattern or a string. For example, how many employees use Gmail accounts in your office, or you
Convert integer to string in PostgreSQL
Publish Date:2025/04/09 Views:167 Category:PostgreSQL
-
This tutorial discusses how to convert an integer to a string in PostgreSQL. Convert integer to string in PostgreSQL Consider a quiz_score table that records the score of each participant in a quiz game. The scores are stored in this table
How to Concatenate Strings in Bash
Publish Date:2025/04/05 Views:65 Category:OPERATING SYSTEM
-
String concatenation is one of the most widely used operations in programming. It refers to connecting two or more strings by putting one string at the end of another string. To concatenate strings in Bash, we can write string variables one
Splitting a string into variables in Bash
Publish Date:2025/03/23 Views:58 Category:OPERATING SYSTEM
-
This article will discuss different ways to split a string into variables in Bash. We will start our discussion with a brief introduction to strings. Later, we will discuss various ways to split a string using Bash examples. Strings in Bash