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:
- Define two numbers: The script initializes two variables,
num1andnum2, with the value10each. - Compare the numbers: The
ifstatement uses the-eqoperator to check if the values ofnum1andnum2are equal. - Execute the true condition: If the condition evaluates to true (the numbers are equal), the script executes the
echocommand to display the message"The numbers are equal.". - Execute the false condition: If the condition evaluates to false (the numbers are not equal), the
elseblock executes, and the script displays the message"The numbers are not equal.".
Output
The numbers are equal.
