How to Compare Strings on Bash
Introduction
Before we begin talking about how to compare strings in Bash, let's briefly understand – What is a String ?
Strings are an essential concept in programming and computer science. A string is a sequence of characters, like letters, numbers, and symbols, enclosed within quotation marks. It can represent words, sentences, or even raw data.
In this tutorial, you will compare strings in Bash. We will also address a few FAQs on how to compare strings in Bash.
Advantages of Strings
- Versatility: Strings allow for a wide range of operations, such as concatenation, substring extraction, and searching, making them suitable for various applications.
- Text manipulation: Strings enable efficient manipulation of textual data, including formatting, parsing, and modifying text content.
- Display and communication: Strings are essential for displaying text on screens and facilitating user interaction and communication between systems.
- Compatibility: Strings can be used in multiple programming languages, ensuring compatibility and portability across different platforms and environments.
- Building block: Understanding strings is crucial as they serve as the fundamental building blocks for text-based operations and data processing in programming.
Comparison Operators
Operators that compare values and return true or false are known as comparison operators. In Bash, the following operators can be used to compare strings:
String1 = string2
andstring1 == string2
- If the operands are equal, the equality operator returns true.
1) When using the test
[
command, use the =
operator.
2) For pattern matching, use the ==
operator with the [[
command.
string1 != string2
- If the operands are not equal, the inequality operator returns true.string1 =~ regex
- If the left operand matches the expanded regular expression on the right, the regex operator returns true.string1 > string2
- If the left operand is greater than the right operand in lexicographical (alphabetical) order, the greater than operator returns true.-z string
- If the string length is zero, this value is true.-n string
- If the string length is non-zero, this value is true.
When comparing strings, keep the following points in mind:
- Between the binary operator and the operands, there must be a blank space.
- To avoid word splitting or globbing, always use double quotes around variable names.
- Variables are not separated by "type" in Bash; depending on the context, variables are interpreted as integers or strings.
Check if Two Strings are Equal
In most circumstances, when comparing strings, you'll want to see if they're equal.
The if statement and the test [
command are used in the following script to check if the strings are equal or not using the =
operator:
#!/bin/bash
VAR1="VegaStack"
VAR2="VegaStack"
if [ "$VAR1" = "$VAR2" ]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
The following output will be printed when the script is run.
Output
Strings are equal.
Here's another script that accepts the user's input and compares it to the strings provided. We'll utilize the [[
command and ==
operator in this example.
#!/bin/bash
read -p "Enter first string: " VAR1
read -p "Enter second string: " VAR2
if [[ "$VAR1" == "$VAR2" ]]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
When prompted, run the script and enter the following strings:
Output
Enter first string: VegaStack
Enter second string: Ubuntu
Strings are not equal.
To compare strings, you can alternatively use the logical operators &&
and or ||
:
[[ "string1" == "string2" ]] && echo "Equal" || echo "Not equal"
Output
Not equal
Check if a String Contains a Substring
There are several methods for determining whether a string contains a substring.
One method is to use asterisk symbols *
to surround the substring, which signifies matching all characters.
#!/bin/bash
VAR='GNU/Linux is an operating system'
if [[ $VAR == *"Linux"* ]]; then
echo "It's there."
fi
The script will echo the following output:
Output
It's there.
Another way is to utilize the regex operator =~
, which is demonstrated below:
#!/bin/bash
VAR='GNU/Linux is an operating system'
if [[ $VAR =~ .*Linux.* ]]; then
echo "It's there."
fi
A period followed by an asterisk .*
matches zero or more instances of any character other than the newline character.
Check if a String is Empty
You'll frequently need to check whether or not a variable is an empty string. The -n
and -z
operators can be used to do this.
#!/bin/bash
VAR=''
if [[ -z $VAR ]]; then
echo "String is empty."
fi
Output
String is empty.
#!/bin/bash
VAR='VegaStack'
if [[ -n $VAR ]]; then
echo "String is not empty."
fi
Output
String is not empty.
Comparing Strings with the Case Operator
To compare strings, you can use the case statement instead of the test operators:
#!/bin/bash
VAR="Arch Linux"
case $VAR in
"Arch Linux")
echo -n "VegaStack matched"
;;
Fedora | CentOS)
echo -n "Red Hat"
;;
esac
Output
VegaStack matched.
Lexicographic Comparison
Lexicographical comparison compares two strings alphabetically by comparing each character in the string sequentially from left to right. This type of comparison is uncommon.
The following scripts lexicographically compare two strings:
#!/bin/bash
VAR1="VegaStack"
VAR2="Ubuntu"
if [[ "$VAR1" > "$VAR2" ]]; then
echo "${VAR1} is lexicographically greater then ${VAR2}."
elif [[ "$VAR1" < "$VAR2" ]]; then
echo "${VAR2} is lexicographically greater than ${VAR1}."
else
echo "Strings are equal"
fi
You will get an output like below:
output
Ubuntu is lexicographically greater than VegaStack.
FAQs to Compare Strings in Bash
Is string comparison case-sensitive in Bash?
Yes, by default, string comparison is case-sensitive in Bash. To perform a case-insensitive comparison, you can use the ==
operator combined with the nocasematch
option.
How can I check if a string is empty in Bash?
To check if a string is empty, you can use the -z
operator. For instance: if [ -z "$str" ]; then echo "String is empty"; fi
.
What if I want to check if a string is not empty?
Use the -n
operator to check if a string is not empty. For example: if [ -n "$str" ]; then echo "String is not empty"; fi
.
How do I compare strings for equality regardless of leading/trailing whitespace?
You can use the xargs
command to trim leading and trailing whitespace before comparing the strings. Example: if [ "$(echo -e "$str1" | xargs)" = "$(echo -e "$str2" | xargs)" ]; then echo "Strings are equal"; fi
.
Can I pattern-match within a string comparison?
Yes, Bash supports pattern matching using the ==
operator and the [[ ]]
construct. Example: if [[ "$str" == *pattern* ]]; then echo "String matches the pattern"; fi
.
How can I perform a numeric comparison of strings in Bash?
To compare strings numerically, use the -eq
(equal), -ne
(not equal), -lt
(less than), -le
(less than or equal), -gt
(greater than), or -ge
(greater than or equal) operators.
What if I want to negate a string comparison?
You can use the !
(logical NOT) operator to negate a string comparison. For example: if [ ! "$str1" = "$str2" ]; then echo "Strings are not equal"; fi
.
Conclusion
In Bash scripting, comparing strings is one of the most basic and commonly used operations. You should have a decent knowledge of how to compare strings in Bash after reading this tutorial.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.