sábado, 21 de mayo de 2022

How to Compare Strings in Bash

 https://linuxize.com/post/how-to-compare-strings-in-bash/

How to Compare Strings in Bash


When writing Bash scripts you will often need to compare two strings to check if they are equal or not. Two strings are equal when they have the same length and contain the same sequence of characters.

This tutorial describes how to compare strings in Bash.

Comparison Operators

Comparison operators are operators that compare values and return true or false. When comparing strings in Bash you can use the following operators:

  • string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal.
    • Use the = operator with the test [ command.
    • Use the == operator with the [[ command for pattern matching.
  • string1 != string2 - The inequality operator returns true if the operands are not equal.
  • string1 =~ regex- The regex operator returns true if the left operand matches the extended regular expression on the right.
  • string1 > string2 - The greater than operator returns true if the left operand is greater than the right sorted by lexicographical (alphabetical) order.
  • string1 < string2 - The less than operator returns true if the right operand is greater than the right sorted by lexicographical (alphabetical) order.
  • -z string - True if the string length is zero.
  • -n string - True if the string length is non-zero.

Following are a few points to be noted when comparing strings:

  • A blank space must be used between the binary operator and the operands.
  • Always use double quotes around the variable names to avoid any word splitting or globbing issues.
  • Bash does not segregate variables by “type”, variables are treated as integer or string depending on the context.

Check if Two Strings are Equal

In most cases, when comparing strings you would want to check whether the strings are equal or not.

The following script uses the if statement and the test [ command to check if the strings are equal or not with the = operator:

#!/bin/bash

VAR1="Linuxize"
VAR2="Linuxize"

if [ "$VAR1" = "$VAR2" ]; then
    echo "Strings are equal."
else
    echo "Strings are not equal."
fi

When the script is executed it will print the following output.

Strings are equal.

Here is another script that takes the input from the user and compares the given strings. In this example, we will use the [[ command and == operator.

#!/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

Run the script and enter the strings when prompted:

Enter first string: Linuxize
Enter second string: Ubuntu
Strings are not equal.

You can also use the logical and && and or || to compare strings:

[[ "string1" == "string2" ]] && echo "Equal" || echo "Not equal"
Not equal

Check if a String Contains a Substring

There are multiple ways to check if a string contains a substring.

One approach is to use surround the substring with asterisk symbols * which means match 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:

It's there.

Another option is to use the regex operator =~ as shown below:

#!/bin/bash

VAR='GNU/Linux is an operating system'
if [[ $VAR =~ .*Linux.* ]]; then
  echo "It's there."
fi

The period followed by an asterisk .* matches zero or more occurrences any character except a newline character.

Check if a String is Empty

Quite often you will also need to check whether a variable is an empty string or not. You can do this by using the -n and -z operators.

#!/bin/bash

VAR=''
if [[ -z $VAR ]]; then
  echo "String is empty."
fi
String is empty.
#!/bin/bash

VAR='Linuxize'
if [[ -n $VAR ]]; then
  echo "String is not empty."
fi
String is not empty.

Comparing Strings with the Case Operator

Instead of using the test operators you can also use the case statement to compare strings:

#!/bin/bash

VAR="Arch Linux"

case $VAR in

  "Arch Linux")
    echo -n "Linuxize matched"
    ;;

  Fedora | CentOS)
    echo -n "Red Hat"
    ;;
esac
Linuxize matched.

Lexicographic Comparison

Lexicographical comparison is an operation where two strings are compared alphabetically by comparing the characters in a string sequentially from left to right. This kind of comparison is rarely used.

The following scripts compare two strings lexicographically:

#!/bin/bash

VAR1="Linuxize"
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

The script will output the following:

Ubuntu is lexicographically greater than Linuxize.

Conclusion

Comparing string is one of the most basic and frequently used operations in Bash scripting. After reading this tutorial, you should have a good understanding of how to compare strings in Bash. You can also check our guide about string concatenation .

If you have any questions or feedback, feel free to leave a comment.

No hay comentarios:

Publicar un comentario