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

#string #css #javascript

How to Compare Strings in Bash
13.10 GEEK