Linux Bash Not Equal “-ne” , “!=” Operators Tutorial

Linux Bash scripting language provides the not equal “-ne” operator in order to compare two values if they are not equal. The not equal operator generally used with the if or elif statements to check not equal and execute some commands.

Not Equal “-ne” Operator Syntax

Linux bash not equal operator is expressed with the “-ne” which is the first letter of “not equal”. Also the “!=” is used to express not equal operator. The “!=” is also popularly used in other programming languages for not equal. The not equal operator is surrounded with the brackets [[ … ]] in order to work.

[ VALUE1 -ne VALUE2 ]
  • VALUE1 is the first value we will compare with the VALUE2. Generally VALUE1 is a bash variable.
  • VALUE2 is the second value we will compare with the VALUE1. Generally the VALUE2 is a value which can be string, number etc.

The not equal comparison operator returns a boolean value which can be True or False. Generally, this boolean value is used with the if or elif statements.

Check If Specified String Is Not Equal

In this example, we will check if the specified string bash variable is not equal to the specified string. We will create the string variable $name and check with the string “ismail”. The -ne operator can not be used with the string types, instead of the != should be used for string comparison.

name="ismail"
 
if [ "$name" != "ismail" ]; then
    echo "Both Strings are NOT Equal."
else
    echo "Both Strings are Equal."
fi

Alternatively, we can check two string variables like below. The variables are named as $myname and $yourname.

myname="ismail"

yourname="john"
 
if [ $myname != $yourname ]; then
    echo "Both Strings are NOT Equal."
else
    echo "Both Strings are Equal."
fi

Check If Specified Number Is Not Equal

The not equal operator can be also used for numbers or integers to compare them each other. In the following example we will check if the bash integer variable $age is not equal to 18.

age=18
 
if [[ $age -ne 18 ]]; then
    echo "Both Numbers are NOT Equal."
else
    echo "Both Numbers are Equal."
fi

Alternatively, two integer or number variables can be compared for their inequality. In the following example, we will check if $myage and $yourage are not equal.

myage=19
 
yourage=19

if [[ $myage -ne -$yourage ]]; then
    echo "Both Numbers are NOT Equal."
else
    echo "Both Numbers are Equal."
fi
READ  List Installed Packages In CentOS, RHEL, Fedora

Leave a Comment