How to Compare strings in Bash Shell

I will explain how to compare two strings to see if they are the same, and to check if a certain string is included.

1. String equality (==)

Basically, you can compare two strings for equality using the == operator.

#!/bin/bash

str1="Hello"
str2="World"

if [ $str1 == $str2 ]
then
    echo "Equal"
else
    echo "Not Equal"
fi

Output:

$ bash example.sh
Not Equal

However, the above code can cause an error when the length of a certain string is 0, that is, when it is Empty.

In this example, an unary operator expected error will occur in the if statement.

#!/bin/bash

str1="Hello"
str2=""

if [ $str1 == $str2 ]
then
    echo "Equal"
else
    echo "Not Equal"
fi

Output:

$ bash example.sh
ex_string_com.sh: line 7: [: Hello: unary operator expected
Not Equal

1.1 Safely compare strings

To safely compare strings, you can enclose the variables in "" so that even if one side is empty, you can compare it in the form of [ "$str1" == "" ] without any issues.

#!/bin/bash

str1="Hello"
str2=""

if [ "$str1" == "$str2" ]
then
    echo "Equal"
else
    echo "Not Equal"
fi

Output:

$ bash example.sh
Not Equal

1.2 Check if a variable is a specific string.

To check if a variable is a certain string, you can compare the variable with the string instead.

#!/bin/bash

str1="Hello"

if [ "$str1" == "Hello" ]
then
    echo "Hello"
else
    echo "Not Hello"
fi

Output:

$ bash example.sh
Hello

2. check if a certain string is included.

You can check if a certain string is included in a string using the two methods below.

  • [[ "$STRING1" == *STRING2* ]]
  • [[ "$STRING1" =~ STRING2 ]]

2.1 Example 1

#!/bin/bash
str='This is the shell script example.'

if [[ "$str" == *shell* ]]; then
  echo "It contains 'shell'"
fi

Output:

$ bash example.sh
It contains 'shell'

2.1 Example 2

#!/bin/bash
str='This is the shell script example.'

if [[ "$str" =~ "shell" ]]; then
  echo "It contains 'shell'"
fi

Output:

$ bash example.sh
It contains 'shell'

3. Check if a string is empty

In [ -z $STRING ], -z is a test operator that returns True when the length of the string is 0.

#!/bin/bash

str1=""

if [ -z $str1 ]
then
    echo "Empty string"
else
    echo "Not empty string"
fi

Output:

$ bash example.sh
Empty string
codechachaCopyright ©2019 codechacha