Bird
Raised Fist0
Bash Scriptingscripting~15 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. Which operator checks if two integers are equal in a bash script?
easy
A. -gt
B. -ne
C. -lt
D. -eq

Solution

  1. Step 1: Understand the meaning of each operator

    -eq means equal, -ne means not equal, -gt means greater than, -lt means less than.
  2. Step 2: Identify the operator for equality

    The operator that checks if two integers are equal is -eq.
  3. Final Answer:

    -eq -> Option D
  4. Quick Check:

    Equality check = -eq [OK]
Hint: Remember: eq means equal, ne means not equal [OK]
Common Mistakes:
  • Confusing -eq with -ne
  • Using == instead of -eq in [ ]
  • Forgetting spaces around operators
2. Which of the following is the correct syntax to check if variable x is greater than 10 in bash?
easy
A. [ $x > 10 ]
B. [ $x -gt 10 ]
C. [ $x -ge 10 ]
D. [ $x => 10 ]

Solution

  1. Step 1: Recall integer comparison operators in bash

    For greater than, bash uses -gt inside [ ]. The symbol > is for string comparison or redirection.
  2. Step 2: Check each option

    [ $x -gt 10 ] uses [ $x -gt 10 ] which is correct syntax for integer greater than check.
  3. Final Answer:

    [ $x -gt 10 ] -> Option B
  4. Quick Check:

    Greater than check uses -gt [OK]
Hint: Use -gt for greater than, not > inside [ ] [OK]
Common Mistakes:
  • Using > instead of -gt inside [ ]
  • Using => instead of -ge
  • Missing spaces around brackets and operators
3. What will be the output of this bash script snippet?
num=5
if [ $num -lt 10 ]; then
echo "Less"
else
echo "More"
fi
medium
A. Less
B. More
C. Syntax Error
D. No output

Solution

  1. Step 1: Evaluate the condition [ $num -lt 10 ]

    num is 5, 5 is less than 10, so condition is true.
  2. Step 2: Determine which branch runs

    Since condition is true, the then branch runs and prints "Less".
  3. Final Answer:

    Less -> Option A
  4. Quick Check:

    5 < 10 is true, prints Less [OK]
Hint: If condition true, then branch runs; else runs otherwise [OK]
Common Mistakes:
  • Confusing -lt with -le
  • Forgetting spaces inside [ ]
  • Using > instead of -lt
4. Identify the error in this bash snippet:
count=3
if [ $count -gt 5 ]
then
  echo "High"
fi
medium
A. No error, script runs fine
B. Missing semicolon or newline after condition
C. Missing spaces around brackets
D. Wrong operator -gt used

Solution

  1. Step 1: Check if the if condition syntax is correct

    The if condition line ends with ] but the next line is then. Bash requires a newline or semicolon after ] before then.
  2. Step 2: Identify the fix

    Add a newline (already present) or a semicolon after ] to separate condition and then. Here newline is present, so syntax is correct.
  3. Step 3: Re-examine the snippet

    Actually, the snippet as shown is correct syntax if newline is present after ] before then. If newline missing, error occurs.
  4. Final Answer:

    No error, script runs fine -> Option A
  5. Quick Check:

    if condition must end with newline or semicolon before then [OK]
Hint: Put newline or semicolon after ] before then [OK]
Common Mistakes:
  • Writing if [ condition ] then on same line without semicolon
  • Forgetting spaces inside [ ]
  • Using > instead of -gt
5. You want to write a bash script that prints "Valid" only if a variable age is between 18 and 30 inclusive. Which condition correctly checks this?
hard
A. [ $age -ge 18 -a $age -le 30 ]
B. [ $age -gt 18 -o $age -lt 30 ]
C. [ $age -ge 18 ] && [ $age -le 30 ]
D. [ $age -gt 18 -a $age -lt 30 ]

Solution

  1. Step 1: Understand the range condition

    We want age >= 18 and age <= 30 inclusive, so both conditions must be true.
  2. Step 2: Analyze each option

    [ $age -ge 18 -a $age -le 30 ] uses -a inside single [ ], which is valid but less recommended. [ $age -gt 18 -o $age -lt 30 ] uses -o (or), which is wrong. [ $age -ge 18 ] && [ $age -le 30 ] uses two separate [ ] with &&, which is correct and clear. [ $age -gt 18 -a $age -lt 30 ] uses > and < (not inclusive) and -a inside [ ].
  3. Final Answer:

    [ $age -ge 18 ] && [ $age -le 30 ] -> Option C
  4. Quick Check:

    Use && with separate [ ] for clear inclusive range [OK]
Hint: Use && with separate [ ] for AND conditions [OK]
Common Mistakes:
  • Using -o (OR) instead of AND
  • Using > and < instead of -ge and -le
  • Combining multiple conditions inside one [ ] with -a (less clear)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard