Arithmetic Expansion with $((...))

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 49 of 205

Bash variables hold text, so a=2 and b=3 do not make a + b equal 5 on their own. Arithmetic expansion is the feature that evaluates a mathematical expression and replaces it with the result. You write the expression inside $((...)), and Bash calculates it with whole numbers (integers) before the command runs.

Syntax

$(( expression ))

The expression can contain numbers, variable names, operators and parentheses. Spaces inside the double parentheses are optional.

echo $((2 + 3))
echo $((10 - 4))
echo $((6 * 7))
echo $((17 / 5))
echo $((17 % 5))
echo $((2 ** 10))

Output:

5
6
42
3
2
1024

Each $((...)) was replaced by its value before echo ran. The operators are addition +, subtraction -, multiplication *, division /, remainder % (also called modulo) and exponentiation **.

Spacing makes no difference to the result:

echo $((1+2))   $(( 1 +  2 ))

Output:

3 3

Integer Division and Remainders

Bash arithmetic works only with integers. Division discards the fractional part instead of rounding:

echo $((7 / 2))
echo $((17 / 5))

Output:

3
3

7 / 2 is 3.5 in ordinary mathematics, but Bash returns 3. The remainder operator % gives what is left over, which is why 17 % 5 is 2: five fits into 17 three times, with 2 left.

Negative numbers are truncated toward zero, and the remainder takes the sign of the left operand:

echo $((-17 / 5))
echo $((-17 % 5))

Output:

-3
-2

The remainder is useful for checking even and odd numbers, wrapping a counter around a limit, and splitting values into units.

Using Variables

Inside $((...)), a variable name is replaced by its value, so the dollar sign is optional:

a=8; b=3
echo $((a + b)) $((a * b)) $(($a - $b))

Output:

11 24 5

All three forms work. Writing a without a dollar sign is the usual style inside arithmetic, because it also allows assignment, as the next section shows.

A variable that is unset counts as 0, and text that is not a number is treated as the name of another variable:

unset zz
echo $((zz + 1))
x=y; y=5
echo $((x + 1))
word=abc
echo $((word + 1))

Output:

1
6
1

zz is unset, so it was 0. The variable x holds the text y, which Bash reads as the name of the variable y and looks up to get 5, so the result is 6. The text abc names a variable that does not exist, so it counted as 0, and the answer is 1. This silent behavior is a common source of surprises when a variable contains a word instead of a number.

Assignment and Increment Operators

Arithmetic expansion can change variables as it evaluates. The compound operators +=, -=, *=, /= and %= update a variable, and ++ and -- add or subtract one.

count=5
echo $((count += 2)); echo $count
echo $((count++)); echo $count
echo $((++count)); echo $count
(( count -= 1 )); echo $count

Output:

7
7
7
8
9
9
8

Reading line by line:

  1. count += 2 set count to 7 and produced 7.
  2. count++ is post-increment. It produced the old value, 7, and then made count equal to 8.
  3. ++count is pre-increment. It made count equal to 9 first and produced 9.
  4. (( count -= 1 )) is the command form, which changes the variable without printing a result. count went from 9 to 8.

Multiple expressions can be joined with a comma. The value of the whole expression is the value of the last one:

echo $((a = 3, b = 4, a * b))

Output:

12

Operator Precedence and Parentheses

Arithmetic follows the usual rules of precedence. Multiplication and division are evaluated before addition and subtraction. Parentheses override the default order.

echo $((2 + 3 * 4))
echo $(((2 + 3) * 4))

Output:

14
20

In the first line, 3 * 4 is calculated first, giving 2 + 12. In the second line, the parentheses force 2 + 3 to be calculated first. Notice that $((( has three opening parentheses: the first two start the arithmetic expansion, and the third is an ordinary grouping parenthesis.

Comparison, Logic and the Ternary Operator

Comparison operators work on numbers and return 1 for true and 0 for false:

echo $((5 > 3)) $((5 < 3)) $((5 == 5)) $((5 != 5))
echo $((1 && 0)) $((1 || 0)) $((!0))

Output:

1 0 1 0
0 1 1

This is the reverse of shell exit statuses, where 0 means success. Inside arithmetic, the convention follows the C language: zero is false and any non-zero value is true.

The ternary operator condition ? value_if_true : value_if_false chooses between two values:

n=7
echo $(( n % 2 == 0 ? 0 : 1 ))

Output:

1

The condition n % 2 == 0 is false for 7, so the expression produced the value after the colon.

Bitwise Operators

Bash supports the operators that work on the binary digits of integers:

echo $((5 & 3)) $((5 | 3)) $((5 ^ 3)) $((~5)) $((1 << 4)) $((256 >> 2))

Output:

1 7 6 -6 16 64

These are AND &, OR |, exclusive OR ^, bitwise NOT ~, left shift << and right shift >>. Shifting left by 4 multiplies by 2 four times, so 1 << 4 is 16. Shifting right by 2 divides 256 by 4. Bit operators appear in permission calculations, flags and low-level scripts.

Numbers in Other Bases

Bash reads a number's base from its prefix:

echo $((0x1F)) $((010)) $((2#1010)) $((16#ff)) $((10#010))

Output:

31 8 10 255 10
Written asBaseMeaning
0x1F16 (hexadecimal)0x prefix
0108 (octal)leading zero
2#10102 (binary)base#digits form
16#ff16any base from 2 to 64
10#01010forces decimal

The leading zero rule catches many people out. 010 is eight, not ten, and a number such as 08 is an error because 8 is not an octal digit:

echo $((08))

Output:

script.sh: line 3: 08: value too great for base (error token is "08")

When the digits come from user input or a date, remove the ambiguity by forcing base 10:

n=08
echo $((10#$n + 1))

Output:

9

10#$n expands to 10#08, which is read as decimal 8.

The (( )) Command and Exit Status

Without the dollar sign, (( expression )) is a command that evaluates the expression and uses its truth value as an exit status. It succeeds (status 0) when the result is non-zero and fails (status 1) when the result is zero.

if (( 5 > 3 )); then echo yes; fi
(( 0 )); echo "status for (( 0 )): $?"
(( 7 )); echo "status for (( 7 )): $?"

Output:

yes
status for (( 0 )): 1
status for (( 7 )): 0

This form is the natural choice in if and while conditions that compare numbers, because it uses the familiar <, > and == operators and does not need $ signs on variable names.

Two older alternatives are worth recognizing:

let "z = 4 * 5"; echo $z
declare -i num
num=3+4
echo $num

Output:

20
7

let evaluates its arguments as arithmetic. A variable declared with declare -i is an integer variable, so Bash evaluates anything assigned to it as arithmetic: num=3+4 stored 7, not the text 3+4.

Whole Numbers Only

The most important limit of Bash arithmetic is that it has no decimals. Writing a decimal number produces an error:

echo $((3.5 + 1))

Output:

script.sh: line 3: 3.5 + 1: syntax error: invalid arithmetic operator (error token is ".5 + 1")

For decimal calculations, hand the work to another tool. bc is a calculator that accepts a setting named scale for the number of decimal places, and awk includes floating-point math:

echo "scale=2; 7 / 2" | bc
awk 'BEGIN { printf "%.2f\n", 7 / 2 }'

Output:

3.50
3.50

bc and awk are separate programs that may not be installed on every minimal system.

Errors and Limits

Division by zero stops the expression with an error and a non-zero exit status:

echo $((5 / 0))

Output:

script.sh: line 3: 5 / 0: division by 0 (error token is "0")

Other invalid input also reports an error instead of guessing:

word2="hello world"
echo $((word2 + 1))
s=12abc
echo $((s + 1))
echo $((2 ** -1))

Output:

script.sh: line 3: hello world: syntax error in expression (error token is "world")
script.sh: line 5: 12abc: value too great for base (error token is "12abc")
script.sh: line 6: 2 ** -1: exponent less than 0 (error token is "1")

Integers have a fixed size. On a 64-bit system, the largest value is 9223372036854775807, and one more wraps around to a large negative number without any warning:

echo $((9223372036854775807))
echo $((9223372036854775807 + 1))

Output:

9223372036854775807
-9223372036854775808

Arithmetic in Strings and Array Indexes

Because $((...)) is an expansion, it works inside double quotes:

echo "Total: $((3 * 4)) items"

Output:

Total: 12 items

Array subscripts are evaluated as arithmetic too, so no $((...)) is needed there, although it is allowed:

arr=(a b c d)
i=1
echo "${arr[i+1]}"
echo "${arr[$((i+2))]}"

Output:

c
d

Practical Examples

Calculate a total, an average and a remainder in a loop:

sum=0
for n in 10 20 35; do sum=$((sum + n)); done
echo "sum=$sum avg=$((sum / 3)) remainder=$((sum % 3))"

Output:

sum=65 avg=21 remainder=2

The loop added each number to sum. The average is whole-number division, so 65 / 3 became 21, and the remainder 2 shows what was lost.

Convert a number of seconds into hours, minutes and seconds:

secs=3725
printf '%02d:%02d:%02d\n' $((secs/3600)) $((secs%3600/60)) $((secs%60))

Output:

01:02:05

The expression secs/3600 gives whole hours (1). secs%3600 removes the hours, leaving 125 seconds, and dividing by 60 gives whole minutes (2). secs%60 is the leftover seconds (5). The %02d format in printf pads each number with a leading zero to two digits.

Roll a dice with the built-in RANDOM variable, which produces a different whole number from 0 to 32767 each time it is read:

r=$((RANDOM % 6 + 1))
(( r >= 1 && r <= 6 )) && echo "dice in range"

Output:

dice in range

RANDOM % 6 gives a value from 0 to 5, and adding 1 shifts it to the range 1 to 6. The second line confirms the result is in range, so the printed text is the same on every run even though the dice value changes.

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 Arithmetic Expansion with $((...)) and get answers drawn from it.

Signed-in readers only.