Bash -ne Operator

The -ne operator in Bash is used to check if two numbers are “not equal” to each other.

This operator is part of the comparison operators provided by Bash for performing numeric comparisons.


Syntax of -ne Operator

The syntax of -ne operator with operands is:

</>
Copy
[ num1 -ne num2 ]

Here, num1 and num2 are the numbers being compared. The condition returns true if the two numbers are not equal.

If the numbers are not equal, the condition evaluates to true; otherwise, it evaluates to false.

The -ne operator is commonly used in conditional statements like if and while.


Examples of -ne (Not Equal To) Operator

Example 1: Checking If Two Predefined Numbers Are Not Equal

In this example, we take two predefined numbers in variables and check if they are not equal.

Program

check_unequal.sh

</>
Copy
#!/bin/bash
# Define two numbers
num1=10
num2=20

# Compare the numbers
if [ $num1 -ne $num2 ]; then
  echo "The numbers are not equal."
else
  echo "The numbers are equal."
fi

Steps:

  1. Define two numbers: The script initializes two variables, num1 and num2, with values 10 and 20, respectively.
  2. Compare the numbers: The if statement uses the -ne operator to check if the values of num1 and num2 are not equal.
  3. Execute the true condition: If the condition evaluates to true (the numbers are not equal), the script executes the echo command to display the message "The numbers are not equal.".
  4. Execute the false condition: If the condition evaluates to false (the numbers are equal), the else block executes, and the script displays the message "The numbers are equal.".
  5. End of script: After determining the inequality and printing the appropriate message, the script terminates.

Output

The numbers are not equal.