0
0
Bash Scriptingscripting~15 mins

Integer comparisons (-eq, -ne, -gt, -lt, -ge, -le) in Bash Scripting - Deep Dive

Choose your learning style9 modes available
Overview - Integer comparisons (-eq, -ne, -gt, -lt, -ge, -le)
What is it?
Integer comparisons in Bash scripting are ways to check if one number is equal to, not equal to, greater than, less than, greater or equal to, or less or equal to another number. These comparisons use special operators like -eq for equal and -gt for greater than. They help scripts make decisions based on numbers. For example, you can check if a user’s input is bigger than 10.
Why it matters
Without integer comparisons, scripts cannot make decisions based on numbers, which limits automation and control. Imagine a script that needs to check if a file size is too big or if a count has reached a limit; without these comparisons, it would not know when to act. This would make scripts less useful and less powerful in real-world tasks.
Where it fits
Before learning integer comparisons, you should understand basic Bash scripting and how to run commands. After mastering these comparisons, you can learn about string comparisons, conditional statements like if-else, and loops that use these comparisons to repeat tasks.
Mental Model
Core Idea
Integer comparisons in Bash let your script ask simple yes-or-no questions about numbers to decide what to do next.
Think of it like...
It's like comparing two piles of coins to see if they have the same amount, or if one pile is bigger or smaller than the other.
  ┌───────────────┐
  │  Number A     │
  └──────┬────────┘
         │ compare using
         │ -eq, -ne, -gt, -lt, -ge, -le
  ┌──────┴────────┐
  │  Number B     │
  └───────────────┘
         ↓
  ┌─────────────────────┐
  │ Result: true or false│
  └─────────────────────┘
Build-Up - 7 Steps
1
FoundationBasics of Integer Comparison Operators
🤔
Concept: Learn what each integer comparison operator means and how to write them in Bash.
In Bash, integer comparisons use these operators inside test brackets [ ] or [[ ]]: -eq means equal -ne means not equal -gt means greater than -lt means less than -ge means greater or equal -le means less or equal Example: if [ "$a" -eq "$b" ]; then echo "Equal"; fi
Result
The script checks if two numbers are equal and prints "Equal" if true.
Understanding these operators is the foundation for making numeric decisions in scripts.
2
FoundationUsing Integer Comparisons in If Statements
🤔
Concept: How to use integer comparisons inside if statements to control script flow.
You can use integer comparisons inside if statements to run commands only when conditions are met. Example: num=5 if [ "$num" -gt 3 ]; then echo "Number is greater than 3" fi
Result
The script prints "Number is greater than 3" because 5 is greater than 3.
Combining comparisons with if statements lets scripts make choices based on numbers.
3
IntermediateCombining Multiple Integer Comparisons
🤔Before reading on: do you think you can combine multiple integer comparisons in one if statement using && or ||? Commit to your answer.
Concept: Learn how to check more than one condition at the same time using logical AND (&&) and OR (||).
You can combine comparisons to check complex conditions. Example: num=7 if [ "$num" -gt 3 ] && [ "$num" -lt 10 ]; then echo "Number is between 4 and 9" fi This checks if num is greater than 3 AND less than 10.
Result
The script prints "Number is between 4 and 9" because 7 fits both conditions.
Knowing how to combine comparisons lets you write smarter scripts that check ranges or multiple rules.
4
IntermediateDifference Between [ ] and [[ ]] for Comparisons
🤔Before reading on: do you think [ ] and [[ ]] behave exactly the same for integer comparisons? Commit to your answer.
Concept: Understand the difference between single [ ] and double [[ ]] brackets in Bash for comparisons.
Single brackets [ ] are the traditional test command and require careful quoting. Double brackets [[ ]] are Bash extensions that are safer and more flexible. Example: if [[ $num -gt 0 ]]; then echo "Positive"; fi Double brackets allow && and || inside without extra brackets.
Result
The script prints "Positive" if num is greater than zero, with less chance of errors.
Using [[ ]] reduces bugs and makes complex conditions easier to write.
5
AdvancedHandling Non-Integer Inputs Safely
🤔Before reading on: do you think integer comparisons in Bash work correctly if variables contain letters or symbols? Commit to your answer.
Concept: Learn why integer comparisons fail with non-integer inputs and how to prevent errors.
If variables contain non-numbers, comparisons like -gt cause errors. Example: num="abc" if [ "$num" -gt 5 ]; then echo "Big"; fi This causes an error: integer expression expected. To avoid this, check if input is a number first: if [[ "$num" =~ ^[0-9]+$ ]]; then if [ "$num" -gt 5 ]; then echo "Big"; fi else echo "Not a number" fi
Result
The script safely handles non-numeric input by printing "Not a number" instead of crashing.
Validating inputs before comparing prevents script failures and improves reliability.
6
AdvancedUsing Arithmetic Expansion for Comparisons
🤔
Concept: Learn how to use Bash arithmetic expansion (( )) as an alternative for integer comparisons.
Bash supports (( )) for arithmetic tests without needing -eq, -gt, etc. Example: num=8 if (( num > 5 )); then echo "Greater than 5" fi This is shorter and easier to read for numbers.
Result
The script prints "Greater than 5" because 8 is greater than 5.
Arithmetic expansion offers a cleaner syntax for numeric comparisons in Bash.
7
ExpertCommon Pitfalls with Integer Comparisons in Scripts
🤔Before reading on: do you think comparing strings with integer operators always works as expected? Commit to your answer.
Concept: Explore subtle bugs like comparing strings as numbers and how Bash treats variables in comparisons.
Bash treats variables as strings by default. Using integer comparisons on strings can cause unexpected results or errors. Example: num="08" if [ "$num" -eq 8 ]; then echo "Equal"; fi This works, but leading zeros can cause issues in some shells. Also, unquoted variables can cause syntax errors if empty: if [ $num -eq 8 ]; then ... # fails if num is empty Always quote variables: if [ "$num" -eq 8 ]; then ... Beware of locale settings affecting numeric comparisons in some environments.
Result
Scripts become more robust and avoid errors by quoting variables and understanding how Bash treats numbers.
Knowing Bash’s treatment of variables and quoting rules prevents subtle bugs in numeric comparisons.
Under the Hood
Bash integer comparisons are implemented by the shell's test command or built-in conditional expressions. When you use operators like -eq or -gt, Bash converts the string values of variables into integers internally and compares their numeric values. If the values are not valid integers, the test fails or errors. The shell uses system calls to evaluate these conditions and returns a true or false exit status to control flow.
Why designed this way?
These operators were designed to provide a simple, readable way to compare numbers in shell scripts without needing external programs. Early shells had limited features, so these operators were added as built-in tests for efficiency and portability. The syntax with a dash (e.g., -eq) was chosen to distinguish numeric tests from string tests and to keep compatibility with the original test command.
┌───────────────┐
│  Script runs  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  test command │
│ or [[ ]] eval │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│ Convert strings to integers  │
│ Check operator (-eq, -gt...) │
└──────┬──────────────────────┘
       │
       ▼
┌───────────────┐
│ Return true/  │
│ false status  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do you think the -eq operator works for comparing decimal numbers like 3.5 and 3.5? Commit to yes or no.
Common Belief:People often believe -eq can compare any numbers, including decimals.
Tap to reveal reality
Reality:-eq only works with integers. It cannot compare decimal or floating-point numbers.
Why it matters:Using -eq with decimals causes errors or wrong results, breaking scripts that expect to handle real numbers.
Quick: do you think unquoted variables in integer comparisons are safe and error-free? Commit to yes or no.
Common Belief:Many think you can safely omit quotes around variables in comparisons.
Tap to reveal reality
Reality:Unquoted variables can cause syntax errors if they are empty or contain spaces.
Why it matters:Scripts may crash or behave unpredictably if variables are not quoted properly.
Quick: do you think [ ] and [[ ]] behave identically for integer comparisons? Commit to yes or no.
Common Belief:Some believe single and double brackets are interchangeable for all tests.
Tap to reveal reality
Reality:[[ ]] is safer and more flexible, allowing complex expressions without extra quoting or escaping.
Why it matters:Using [ ] in complex conditions can cause bugs or require complicated syntax.
Quick: do you think Bash treats numbers with leading zeros as decimal numbers? Commit to yes or no.
Common Belief:People often assume numbers with leading zeros are treated as normal decimal numbers.
Tap to reveal reality
Reality:In some shells, numbers with leading zeros are treated as octal (base 8), which can cause unexpected results.
Why it matters:Scripts comparing numbers with leading zeros may behave incorrectly or fail silently.
Expert Zone
1
Integer comparisons in Bash are actually string comparisons under the hood, but the test command converts strings to integers carefully, which can cause subtle bugs if inputs are malformed.
2
The [[ ]] syntax is a Bash extension that avoids many quoting pitfalls and allows combining conditions with && and || without extra brackets, improving script readability and safety.
3
Leading zeros in numbers can cause octal interpretation, which is rarely intended and can silently break numeric logic in scripts.
When NOT to use
Avoid using Bash integer comparisons for floating-point numbers or complex numeric operations; instead, use tools like bc or awk for precise math. Also, for string comparisons, use string operators or regex instead of integer operators.
Production Patterns
In production scripts, integer comparisons are often combined with input validation to prevent errors. Scripts use (( )) arithmetic expressions for cleaner syntax and prefer [[ ]] for safer conditionals. Complex numeric logic is offloaded to specialized tools, while Bash handles control flow.
Connections
Conditional Statements
Integer comparisons are the building blocks used inside conditional statements like if-else to control script flow.
Understanding integer comparisons helps grasp how scripts decide what actions to take based on numeric conditions.
Regular Expressions
Input validation for integer comparisons often uses regular expressions to ensure variables contain only digits before comparing.
Knowing regex helps prevent errors by filtering inputs before numeric tests.
Decision Making in Psychology
Both integer comparisons in scripts and human decision making involve evaluating conditions to choose actions.
Recognizing this similarity shows how computers mimic simple human choices using numeric tests.
Common Pitfalls
#1Using unquoted variables in integer comparisons causing syntax errors.
Wrong approach:if [ $num -eq 5 ]; then echo "Equal"; fi
Correct approach:if [ "$num" -eq 5 ]; then echo "Equal"; fi
Root cause:Not quoting variables means if $num is empty or contains spaces, the test command receives invalid syntax.
#2Trying to compare decimal numbers with integer operators.
Wrong approach:if [ "$num" -eq 3.5 ]; then echo "Equal"; fi
Correct approach:echo "$num == 3.5" | bc -l | grep -q 1 && echo "Equal"
Root cause:Integer operators only work with whole numbers; decimals require external tools like bc.
#3Using [ ] with complex conditions without proper syntax.
Wrong approach:if [ "$num" -gt 3 && "$num" -lt 10 ]; then echo "Between"; fi
Correct approach:if [ "$num" -gt 3 ] && [ "$num" -lt 10 ]; then echo "Between"; fi
Root cause:[ ] does not support && inside; each condition must be separate.
Key Takeaways
Integer comparisons in Bash use special operators like -eq and -gt to compare numbers and control script decisions.
Always quote variables in comparisons to avoid syntax errors when variables are empty or contain spaces.
Use [[ ]] or (( )) for safer and cleaner numeric comparisons in Bash scripts.
Integer comparisons only work with whole numbers; for decimals, use external tools like bc.
Understanding these comparisons is essential for writing reliable and powerful Bash scripts that respond to numeric conditions.