Bash -eq Operator

The -eq operator in Bash is used to check if two numbers are equal.

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


Syntax of Equal Operator

</>
Copy
[ num1 -eq num2 ]

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

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

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


Examples of -eq (Equal To)Operator

Example 1: Checking Equality Between Two Predefined Numbers

In this example, we take two predefined in two variables, or say hard coded numbers, and check they are equal.

Program

check_equal.sh

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

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

Steps:

  1. Define two numbers: The script initializes two variables, num1 and num2, with the value 10 each.
  2. Compare the numbers: The if statement uses the -eq operator to check if the values of num1 and num2 are equal.
  3. Execute the true condition: If the condition evaluates to true (the numbers are equal), the script executes the echo command to display the message "The numbers are equal.".
  4. Execute the false condition: If the condition evaluates to false (the numbers are not equal), the else block executes, and the script displays the message "The numbers are not equal.".

Output

The numbers are equal.