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.