Numerical Comparison Operators

Numerical comparison operators are used to compare numbers within square brackets.

Operators:

  • -eq : Equal to
  • -ne : Not equal to
  • -lt : Less than
  • -le : Less than or equal to
  • -gt : Greater than
  • -ge : Greater than or equal to

Example:

#!/bin/bash

if [ $1 -eq 100 ]; then
echo "The number is 100."
elif [ $1 -lt 100 ]; then
echo "The number is less than 100."
else
echo "The number is greater than 100."
fi

Output:

$ ./script.sh 100
The number is 100.

$ ./script.sh 50
The number is less than 100.

$ ./script.sh 150
The number is greater than 100.

Using Square Brackets in Bash

Square brackets ([ and ]) are essential components in Bash scripting. They are used for a variety of purposes, including conditional expressions, string and numerical comparisons, and file tests. This article provides a comprehensive overview of square brackets in Bash, exploring their uses and functionalities.

Similar Reads

2. Overview of Square Brackets in Bash

In Bash, square brackets are used for test constructs. There are two main forms:...

3. Conditional Expressions with Square Brackets

Conditional expressions are used to test conditions and control the flow of the script based on the test results....

4. String Comparison Operators

String comparison operators are used to compare strings within square brackets....

5. Numerical Comparison Operators

Numerical comparison operators are used to compare numbers within square brackets....

6. File Test Operators

File test operators are used to check properties of files....

7. Advanced Usage Examples

Advanced usage examples demonstrate more complex conditions and combinations of tests....

8. Best Practices and Tips

Always quote variables to prevent word splitting and globbing. Use double square brackets for more complex conditions and to avoid some pitfalls of single square brackets. Use parentheses to group conditions for readability and logical grouping. Prefer -e over other file test operators when simply checking for existence....

9. Conclusion

Understanding how to use square brackets in Bash is crucial for writing effective and efficient scripts. This article covered the basics and advanced usage of square brackets, including string and numerical comparisons, file tests, and best practices....

Using Square Brackets in Bash – FAQs

What is the difference between single and double square brackets in Bash?...