Integer Comparisons in Bash

Su Suriya Ravichandran Updated 06 Dec 2026
16 min read ·Lesson 73 of 205

Scripts constantly compare numbers: how many arguments were passed, how many lines a file has, how full a disk is, how many times a loop has run. Bash has no separate number type. Every variable holds text, and the shell decides whether to treat that text as a number only at the moment it is used. For that reason, comparing numbers needs its own set of operators, different from the string operators in lesson 70. This lesson covers the integer operators for [ ] and [[ ]], and the (( )) arithmetic command, which is the most natural way to write numeric conditions in Bash.

Understanding the Concept

An integer comparison converts both sides to whole numbers and compares their values. This is not the same as comparing characters. As text, "10" and "9" are compared character by character, and 1 comes before 9, so "10" sorts before "9". As numbers, ten is larger than nine. Choosing the wrong kind of operator is one of the most common sources of confusing results in shell scripts.

Bash supports whole numbers only. There are no decimals in Bash arithmetic, so a value such as 3.5 cannot be compared with these operators. For fractions, scripts call an external tool such as bc or awk.

The Six Integer Operators

Inside [ ] and [[ ]], integer comparisons use short word-like operators, which come from the names of the comparison:

OperatorMeaningName
-eqequalequal
-nenot equalnot equal
-ltless thanless than
-leless than or equalless than or equal
-gtgreater thangreater than
-gegreater than or equalgreater than or equal

The symbols <, > and == are not used here, because inside [ ] the characters < and > are redirection symbols, and == compares strings.

Basic Example

a=10
b=20

[ "$a" -eq "$b" ]; echo "10 -eq 20: $?"
[ "$a" -ne "$b" ]; echo "10 -ne 20: $?"
[ "$a" -lt "$b" ]; echo "10 -lt 20: $?"
[ "$a" -le 10 ];   echo "10 -le 10: $?"
[ "$a" -gt "$b" ]; echo "10 -gt 20: $?"
[ "$a" -ge 10 ];   echo "10 -ge 10: $?"

Output:

10 -eq 20: 1
10 -ne 20: 0
10 -lt 20: 0
10 -le 10: 0
10 -gt 20: 1
10 -ge 10: 0

Understanding the Example

Each line runs one comparison and then prints $?, the exit status. As in lesson 66, status 0 means the condition is true and 1 means it is false. Ten is not equal to twenty, so -eq returns 1 and -ne returns 0. Ten is less than twenty, so -lt is true. It is not greater than twenty, so -gt is false. The last two lines show the inclusive forms: -le and -ge are both true when the two numbers are the same.

Every variable is quoted. That follows the rule from lesson 55, and for numbers it prevents a specific failure shown later in this lesson when a variable is empty.

Numbers Versus Strings

The same two values can give opposite answers depending on the operator:

[ 10 -gt 9 ];     echo "10 -gt 9 as numbers: $?"
[ "10" \> "9" ];  echo "10 > 9 as strings: $?"

Output:

10 -gt 9 as numbers: 0
10 > 9 as strings: 1

As numbers, ten is greater than nine. As strings, 10 comes before 9 in dictionary order, so 0 is false. The backslash in 1 stops the shell from treating > as a redirection, as lesson 70 explained.

Leading zeros expose the same difference:

[ "10" = "010" ];  echo "10 = 010 as strings: $?"
[ 10 -eq 010 ];    echo "10 -eq 010 as numbers: $?"

Output:

10 = 010 as strings: 1
10 -eq 010 as numbers: 0

The text is different, but inside [ ] the number 010 is read as decimal ten, so the numeric comparison is true. Remember this when reading numbers from input: use -eq and the other integer operators for numbers, and = only for exact text.

What the Operators Accept

The integer operators in [ ] are strict. Both sides must be whole numbers, optionally with a sign:

[ -5 -lt 0 ];   echo "-5 -lt 0: $?"
[ "+7" -eq 7 ]; echo "+7 -eq 7: $?"

Output:

-5 -lt 0: 0
+7 -eq 7: 0

Anything else produces an error and status 2:

[ abc -eq 5 ];    echo "abc: $?"
[ 3.5 -gt 3 ];    echo "3.5: $?"
[ "" -eq 0 ];     echo "empty: $?"

Output:

bash: [: abc: integer expression expected
abc: 2
bash: [: 3.5: integer expression expected
3.5: 2
bash: [: : integer expression expected
empty: 2

Inside a script, the messages begin with the script's name and a line number, as in ./check.sh: line 7:. The pattern is the same for every case: the shell cannot read the value as an integer, prints integer expression expected, and returns status 2. As lesson 66 explained, an if treats any non-zero status as false, so the condition quietly takes the else branch while the message appears on standard error. That makes these errors easy to miss in a script that prints a lot of other output.

Two details are worth knowing. First, a hexadecimal number such as 0x10 is rejected inside [ ]:

[ 0x10 -eq 16 ]; echo "0x10: $?"

Output:

bash: [: 0x10: integer expression expected
0x10: 2

Second, Bash accepts surrounding spaces, so [ " 7" -eq 7 ] and [ "7 " -eq 7 ] are both true. This is convenient when a value comes from a tool that pads its output with blanks.

Unquoted Empty Variables

An unquoted empty variable disappears, which leaves a broken command:

x=
[ $x -eq 0 ]; echo "status: $?"

Output:

bash: [: -eq: unary operator expected
status: 2

The shell passes only -eq and 0 to [, which then cannot work out what to do. Quoting the variable keeps the empty argument in place, so the test fails with the integer error shown above rather than with a confusing syntax message. A script that needs to handle an empty value safely can provide a default with parameter expansion from lesson 45:

count=
[ "${count:-0}" -eq 0 ]; echo "empty treated as 0: $?"

Output:

empty treated as 0: 0

Large Numbers

Bash integers are 64-bit signed values. The largest value is 9223372036854775807. One more than that is not accepted:

[ 9223372036854775807 -gt 1 ]; echo "largest: $?"
[ 9223372036854775808 -gt 1 ]; echo "one over: $?"

Output:

largest: 0
bash: [: 9223372036854775808: integer expression expected
one over: 2

Leading Zeros and Number Bases

Inside [ ], a number with leading zeros is read as an ordinary decimal. In the arithmetic forms covered next, a leading zero means something different: it marks an octal (base 8) number. This difference matters because numbers such as 08 and 09 often appear in dates and times:

[ 08 -eq 8 ]; echo "[ 08 -eq 8 ]: $?"
[ 010 -eq 8 ]; echo "[ 010 -eq 8 ]: $?"

Output:

[ 08 -eq 8 ]: 0
[ 010 -eq 8 ]: 1

In [ ], 010 is decimal ten, so it is not equal to eight. In (( )) the same text is octal, which gives a different answer, as the next section shows. Lesson 34 described the 10# prefix, which forces a number to be read as decimal.

Comparing Inside Double Brackets

The [[ ]] keyword accepts the same six operators:

[[ 10 -lt 20 ]]; echo "[[ 10 -lt 20 ]]: $?"

Output:

[[ 10 -lt 20 ]]: 0

It also does not require quoting of variables, since [[ ]] does not split words (lesson 69). There is one important difference. Inside [[ ]], each side of -eq is evaluated as an arithmetic expression. That has surprising consequences:

[[ abc -eq 0 ]]; echo "abc -eq 0: $?"
n=3
[[ n -eq 3 ]];   echo "name n -eq 3: $?"
[[ 1+2 -eq 3 ]]; echo "1+2 -eq 3: $?"
[[ 08 -eq 8 ]];  echo "08 -eq 8: $?"

Output:

abc -eq 0: 0
name n -eq 3: 0
1+2 -eq 3: 0
bash: [[: 08: value too great for base (error token is "08")
08 -eq 8: 1

A word such as abc is treated as the name of a variable. Because no variable called abc is set, its value counts as zero, so the test is true and no error appears. The bare name n is replaced by the value of the variable, and 1+2 is calculated. Leading zeros now mean octal, and 08 is not a valid octal number, so the test fails with an error.

These behaviors can hide mistakes. A typo in a variable name, or a non-numeric value, silently becomes 0. For that reason, when input might not be numeric, check it first or use (( )) deliberately.

The Arithmetic Command (( ))

The (( )) compound command evaluates an arithmetic expression using C-like syntax. It returns status 0 when the result is not zero and status 1 when the result is zero, so that a true comparison counts as success. Inside it, you can use the familiar symbols and you do not need $ in front of variable names:

a=10
b=20

(( 10 < 20 ));         echo "10 < 20: $?"
(( a > b ));           echo "a > b: $?"
(( a == 10 ));         echo "a == 10: $?"
(( a != b ));          echo "a != b: $?"
(( a * 2 == b ));      echo "a * 2 == b: $?"
(( a % 3 == 1 ));      echo "a % 3 == 1: $?"
(( a >= 10 && b <= 20 )); echo "both conditions: $?"

Output:

10 < 20: 0
a > b: 1
a == 10: 0
a != b: 0
a * 2 == b: 0
a % 3 == 1: 0
both conditions: 0

You can use the full set of operators <, <=, >, >=, == and !=, the arithmetic operators +, -, *, / and %, and the logical operators &&, || and !. There is no need to quote anything, and the symbols are not treated as redirections, because the shell reads everything between the double parentheses as one expression.

Because the result of the expression decides the exit status, a plain number works as a condition:

(( 0 )); echo "(( 0 )): $?"
(( 5 )); echo "(( 5 )): $?"

Output:

(( 0 )): 1
(( 5 )): 0

Inside (( )), non-numeric words and unset variables count as zero, in the same way as in [[ ]]:

unset u
(( u == 0 )); echo "unset variable: $?"
s=abc
(( s == 0 )); echo "text variable: $?"

Output:

unset variable: 0
text variable: 0

Leading Zeros in Arithmetic

In (( )), a leading zero makes the number octal, and a leading 0x makes it hexadecimal:

(( 010 == 8 ));    echo "010 == 8: $?"
(( 0x10 == 16 ));  echo "0x10 == 16: $?"
(( 08 == 8 ));     echo "08 == 8: $?"
(( 10#08 == 8 ));  echo "10#08 == 8: $?"

Output:

010 == 8: 0
0x10 == 16: 0
bash: ((: 08: value too great for base (error token is "08")
08 == 8: 1
10#08 == 8: 0

The number 010 is octal and equals eight. The number 08 is an error, because 8 is not a digit in base 8. The prefix 10# fixes that by declaring the number to be base 10. Use it whenever a value that may begin with zero comes from a date, a time, or a file name.

Assignments Inside (( ))

An expression in (( )) can contain an assignment, and the value of the assignment decides the exit status:

n=5
(( n = 3 )); echo "(( n = 3 )) status $? n=$n"
(( n == 3 )); echo "(( n == 3 )) status $?"
(( n = 0 )); echo "(( n = 0 )) status $? n=$n"

Output:

(( n = 3 )) status 0 n=3
(( n == 3 )) status 0
(( n = 0 )) status 1 n=0

The first line assigns 3 and returns success. The last line assigns 0, which is a false value, so the command returns status 1 even though nothing went wrong. A single = in a condition changes the variable instead of comparing, so (( n = 3 )) is rarely what you want when you meant (( n == 3 )).

Increments and set -e

The same rule creates a trap with counters. The post-increment (( i++ )) has the value of i before the increment, so starting from zero it evaluates to 0, which means status 1:

i=0; (( i++ )); echo "i++ from 0: status $? i=$i"
i=0; (( ++i )); echo "++i from 0: status $? i=$i"

Output:

i++ from 0: status 1 i=1
++i from 0: status 0 i=1

In a script that uses set -e (lesson 119), that failing status ends the script:

set -e
i=0
(( i++ ))
echo "not reached when i starts at 0"

The script stops silently at the (( i++ )) line with exit status 1. Using the assignment form avoids the problem, because arithmetic expansion is not a command and has no exit status of its own:

set -e
i=0
i=$((i + 1))
echo "i=$i reached"
(( i += 1 ))
echo "i=$i reached"

Output:

i=1 reached
i=2 reached

The first form uses arithmetic expansion from lesson 49. The second uses (( i += 1 )), whose value is the new, non-zero number, so it succeeds.

Using Integer Tests in Conditions

Either style works in an if:

count=7

if [ "$count" -gt 5 ]; then
    echo "more than 5"
fi

if (( count > 5 )); then
    echo "more than 5 (arithmetic)"
fi

if [ "$count" -ge 1 ] && [ "$count" -le 10 ]; then
    echo "between 1 and 10"
fi

if (( count >= 1 && count <= 10 )); then
    echo "between 1 and 10 (arithmetic)"
fi

Output:

more than 5
more than 5 (arithmetic)
between 1 and 10
between 1 and 10 (arithmetic)

The (( )) versions are shorter and read like ordinary mathematics. The [ ] versions work in more shells, which matters for portability. Range checks need two comparisons joined by &&, covered in lesson 74.

Comparing Numbers from Commands

A common task is to compare a number printed by another command. Beware that many commands print more than just the number:

printf 'a\nb\nc\n' > lines.txt

n=$(wc -l < lines.txt)
echo "n=[$n]"
[ "$n" -ge 3 ] && echo "at least 3 lines"

m=$(wc -l lines.txt)
echo "m=[$m]"
[ "$m" -ge 3 ]; echo "status: $?"

Output:

n=[3]
at least 3 lines
m=[3 lines.txt]
bash: [: 3 lines.txt: integer expression expected
status: 2

When wc -l reads from standard input (< lines.txt), it prints only the count. When given the file name as an argument, it prints the count followed by the name, which is not an integer. Redirecting input, as lesson 58 showed, keeps the output clean. The exit status of a command can also be compared directly:

grep -q zzz lines.txt
status=$?
[ "$status" -eq 1 ] && echo "grep reported no match"

Output:

grep reported no match

The value is saved to a variable right away, because $? changes after every command.

Checking That Input Is an Integer

When a value comes from a user or a file, test it before comparing. A regular expression with [[ ]] does the job:

is_integer() {
    [[ $1 =~ ^-?[0-9]+$ ]]
}

for v in 42 -7 3.5 abc "" 007; do
    if is_integer "$v"; then
        echo "'$v' is an integer"
    else
        echo "'$v' is not an integer"
    fi
done

Output:

'42' is an integer
'-7' is an integer
'3.5' is not an integer
'abc' is not an integer
'' is not an integer
'007' is an integer

The pattern allows an optional minus sign followed by one or more digits, anchored at both ends. The function's exit status comes from the [[ ]] test, so it can be used directly after if. Note that 007 passes the check, so use 10# before doing arithmetic on it if leading zeros are possible.

Portability

Under Dash, which is what sh runs on Debian and Ubuntu, the six operators -eq, -ne, -lt, -le, -gt and -ge work, as does arithmetic expansion $(( )):

dash -lt: 0
dash if ok
dash arith ok

Two differences appear. The (( )) command does not exist in Dash. A line such as (( 1 < 2 )) is read as a subshell containing a redirection, and fails with cannot open 2: No such file. Dash also treats 0x10 as an error in [ ] (Illegal number: 0x10), as Bash does. For scripts that must run under sh, write [ "$n" -lt 10 ] and compute with $(( )). Lessons 188 and 189 cover the differences in detail.

Practical Applications

A loop that repeats while a counter is below a limit:

count=1

while [ "$count" -le 3 ]; do
    echo "round $count"
    count=$((count + 1))
done

Output:

round 1
round 2
round 3

A loop that stops after a fixed number of attempts, using until from lesson 81:

attempts=0
max=3

until [ "$attempts" -ge "$max" ]; do
    attempts=$((attempts + 1))
    echo "attempt $attempts of $max"
done

Output:

attempt 1 of 3
attempt 2 of 3
attempt 3 of 3

A script that requires exactly two arguments, using $# from lesson 43:

#!/usr/bin/env bash

if [ "$#" -ne 2 ]; then
    echo "usage: $0 first second" >&2
    exit 2
fi

echo "got $1 and $2"

Run as bash args.sh one, it prints the usage message and exits with status 2. Run as bash args.sh one two, it prints got one and two.

A grading function built with an if chain from lesson 67:

score=$1

if [ "$score" -ge 90 ]; then
    echo "A"
elif [ "$score" -ge 80 ]; then
    echo "B"
elif [ "$score" -ge 70 ]; then
    echo "C"
else
    echo "F"
fi

For the scores 95, 85, 72 and 40, the script prints A, B, C and F. The branches are tested from the highest threshold downwards, so each score ends up in the first branch it qualifies for.

A disk-space warning, using df and tr to extract the percentage:

used=$(df --output=pcent / | tail -n 1 | tr -dc '0-9')
echo "used=[$used]"

if (( used > 90 )); then
    echo "disk almost full"
else
    echo "disk ok"
fi

On the test machine it printed used=[29] and disk ok. The tr -dc '0-9' command deletes every character that is not a digit, which removes the % sign and leading spaces that df prints. The --output option belongs to GNU df, so this exact command does not work on macOS.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Integer Comparisons in Bash and get answers drawn from it.

Signed-in readers only.