Bash -lt Operator
The -lt operator in Bash is used to check if the first number is “less than” the second number.
This operator is part of the comparison operators provided by Bash for performing numeric comparisons.
Syntax of -lt Operator
The syntax of -lt operator with the two operands is:
</>
Copy
[ num1 -lt num2 ]
Here, num1 and num2 are the numbers being compared. The condition returns true if num1 is less than num2.
If the first number is less, the condition evaluates to true; otherwise, it evaluates to false.
The -lt operator is commonly used in conditional statements like if and while.
Examples of -lt (Less Than) Operator
Example 1: Checking if a Number is Less Than Another
In this example, we take two predefined numbers and check if the first number is less than the second number using the -lt operator.
Program
check_less.sh
</>
Copy
#!/bin/bash
# Define two numbers
num1=10
num2=15
# Compare the numbers
if [ $num1 -lt $num2 ]; then
echo "The first number is less."
else
echo "The first number is not less."
fi
Steps:
- Define two numbers: The script initializes two variables,
num1andnum2, with values10and15, respectively. - Compare the numbers: The
ifstatement uses the-ltoperator to check if the value ofnum1is less thannum2. - Execute the true condition: If the condition evaluates to true (the first number is less), the script executes the
echocommand to display the message"The first number is less.". - Execute the false condition: If the condition evaluates to false (the first number is not less), the
elseblock executes, and the script displays the message"The first number is not less.".
Output
The first number is less.
