Understanding Different Results of Arithmetic Operations in Linux: Case 1 vs. Case 2

Abstract: Resolve inconsistent Bash arithmetic results by replacing the legacy expr command with $(( )) to ensure correct operator precedence and avoid exit code errors.

Created: 2026-09-27 by
Bash arithmetic operations yield different results depending on whether you use the expr command, the $((...)) syntax, or the let builtin because of how each tool handles operator precedence, quoting, and return codes. Understanding these distinctions prevents subtle bugs in shell scripts where integer overflow or string interpretation leads to unexpected outcomes.

The Two Common Cases

When developers encounter inconsistent arithmetic results in Bash, they are usually comparing two specific approaches. Case 1 typically involves using the legacy expr command, while Case 2 utilizes modern Bash built-in arithmetic expansion like $(( ... )). These methods look similar but behave fundamentally differently regarding parsing and execution context. In Case 1, users often write something like:
result=$(expr 10 + 5)
Or mistakenly omit spaces:
result=$(expr 10+5)
In Case 2, the standard modern approach is:
result=$(( 10 + 5 ))
The confusion arises because both attempt to perform addition, yet one may fail silently, throw an error, or produce a string result instead of an integer, depending on the shell environment and version.

Why expr Produces Different Results

The expr utility is a standalone external command, not a Bash builtin. This distinction is critical for performance and behavior. Because it is external, it relies heavily on shell word splitting and globbing before the command even executes. One major source of error in Case 1 is spacing. The expr command requires spaces around operators. If you write expr 10+5, it does not interpret this as "add five to ten." Instead, it treats 10+5 as a single literal string argument. Consequently, the output might be the string itself or an error indicating that the argument is invalid for numeric evaluation. Furthermore, expr returns its exit status based on the success of the operation. If the expression evaluates to zero, expr returns an exit code of 1 (failure). In conditional statements like if [ $(expr 10 - 10) -eq 0 ], this can cause logic errors because the command fails before the comparison even happens. This is a common pitfall for beginners migrating from older Bourne shell scripts. Another issue with expr is operator precedence. It evaluates expressions strictly left-to-right without standard mathematical precedence rules for multiplication and division over addition. For example, expr 10 + 5 \* 2 calculates (10 + 5) * 2 = 30, whereas most programming languages would calculate 10 + (5 * 2) = 20. To get correct precedence with expr, you must rely on parentheses which also require escaping: \( and \).

Why $(( )) Yields Consistent Results

Case 2, using $(( ... )), is the preferred method in Bash because it is a builtin feature. This means it is processed directly by the shell interpreter, avoiding the overhead of spawning an external process. The syntax inside double parentheses follows standard C-like arithmetic rules. Multiplication and division have higher precedence than addition and subtraction. You do not need to escape parentheses, and spaces are optional, making the code cleaner and less prone to syntax errors.
echo $(( 10 + 5 * 2 ))
This correctly outputs 20. Additionally, $(( ... )) always returns an integer value. If you assign it to a variable, that variable holds a numeric type, allowing for further arithmetic operations without conversion. There is no risk of the "zero equals failure" exit code issue that plagues expr. For more complex calculations involving floating-point numbers, neither expr nor $(( )) works natively. However, for pure integer arithmetic, $(( )) is robust, fast, and portable across all POSIX-compliant shells including Bash, Zsh, and Dash.

Best Practices for Shell Arithmetic

To avoid the pitfalls described in Case 1 and Case 2, adopt the following practices in your Linux scripts:
  • Use Builtins: Always prefer $(( ... )) or let over expr. The let command is another builtin that evaluates arithmetic expressions, but $(( )) is generally more readable when assigning values.
  • Avoid External Commands: Every time you call expr, you spawn a new process. In loops, this significantly slows down script execution compared to using built-in arithmetic.
  • Handle Quoting Carefully: When using variables in arithmetic, ensure they are expanded correctly. $(($var1 + $var2)) works, but expr $var1 + $var2 requires careful handling if the variables contain special characters or are empty.
  • Check for Integer Overflow: Bash uses signed 64-bit integers. If your calculation exceeds this range, the result will wrap around unpredictably. Monitor large datasets closely.
If you are dealing with floating-point math, consider using bc or awk as external tools, since Bash does not support them natively. For example, echo "scale=2; 10/3" | bc provides decimal precision. For those managing configurations or aliases that might interfere with script execution, understanding how shell options affect commands is crucial. You might find related insights in Troubleshooting Linux RHEL 7, which covers broader execution contexts. Similarly, if your arithmetic results involve string manipulation or file paths, knowing how to handle special characters is vital. See Replacing Special Characters in a Text File with Linux Command Line for guidance on data sanitization.

Frequently Asked Questions

Can I use floating point numbers with $(( ))?

No, Bash arithmetic expansion only supports integers. If you attempt to use decimals like $(( 10.5 + 5 )), Bash will report a syntax error. You must use external tools like bc, awk, or python for floating-point calculations.

Why does expr return exit code 1 when the result is 0?

This is by design in the expr utility. An exit code of 0 indicates success, but in many logical contexts, a result of 0 is considered false. Therefore, expr returns 1 (failure) if the evaluated expression is zero, and 0 (success) otherwise. This can break if statements that expect the command's exit code to reflect the truthiness of the result.

Is there a performance difference between expr and $(( ))?

Yes, significant differences exist. expr is an external binary, meaning Bash must fork a new process for every calculation. In tight loops, this overhead can drastically slow down script execution. $(( )) is a builtin, so it runs entirely within the shell process, offering near-instantaneous evaluation.

What happens if I forget spaces in expr?

If you write expr 10+5, expr sees a single argument 10+5. It will likely print 10+5 back to stdout or throw an error about invalid arguments, rather than performing addition. Spaces are mandatory delimiters for expr to distinguish between operands and operators.

How do I handle modulo operations in Bash?

You can use the percent sign % inside $(( )) just like in C. For example, $(( 10 % 3 )) returns 1. With expr, you must escape the percent sign as \% because the shell interprets unescaped % as part of filename expansion or other special sequences.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More