Arithmetic
| Since: | expr(外部コマンド) | POSIX(sh互換) |
|---|---|---|
| (( )) / let | Bash(bash拡張) |
Shell scripts offer several ways to perform arithmetic. By combining bash's built-in (( )) and let, the POSIX-compliant external command expr, and the arithmetic expansion syntax $(( )), you can write integer calculations in a flexible way.
Basics of (( ))
(( )) is bash's built-in arithmetic evaluation syntax. It supports C-style operators. If the result is non-zero, the exit status is 0 (success); if the result is zero, the exit status is 1 (failure), so it can also be used as a condition in if statements and while loops.
| Syntax | Description |
|---|---|
(( expr )) | Evaluates an arithmetic expression. If the result is non-zero, exit status is 0 (true); if zero, exit status is 1 (false). |
(( a = expr )) | Assigns the result of an arithmetic expression to variable a. Variable names can be written without $. |
(( a += b )) | Compound assignment operators (+= -= *= /= %=) are available. |
if (( expr )); then | Uses an arithmetic expression as a condition. Cleaner than using [ ] with -eq. |
while (( expr )); do | Uses an arithmetic condition as the loop continuation condition. |
Increment and Decrement
(( )) supports the same increment and decrement operators as C. Prefix (++i) and postfix (i++) differ in the timing of evaluation.
| Syntax | Description |
|---|---|
(( i++ )) | Postfix increment. Returns the current value of i, then increments i by 1. |
(( ++i )) | Prefix increment. Increments i by 1, then returns the new value. |
(( i-- )) | Postfix decrement. Returns the current value of i, then decrements i by 1. |
(( --i )) | Prefix decrement. Decrements i by 1, then returns the new value. |
(( i += 5 )) | Increases i by 5. Equivalent to (( i = i + 5 )). |
(( i -= 3 )) | Decreases i by 3. |
let
let is a bash built-in arithmetic evaluation command. It has the same functionality as (( )) but is written as a command invocation. Multiple expressions can be placed on one line.
| Syntax | Description |
|---|---|
let a=1+2 | Evaluates an arithmetic expression and assigns the result to variable a. No spaces are allowed around =. |
let "a = 1 + 2" | Wrapping in quotes allows spaces for improved readability. |
let a++ b-- | Multiple expressions separated by spaces can be evaluated at once. |
let a=b*c | Other operators such as multiplication are also available. * is not expanded without quotes. |
(( )) is more readable and modern than let. Prefer (( )) in new scripts.
expr (External Command)
expr is an external command. It is POSIX-standard and works in sh environments, but the syntax becomes verbose due to mandatory space-separated arguments and the need to escape *. In bash environments, prefer $(( )).
| Syntax | Description |
|---|---|
expr 1 + 2 | Addition. Operators and operands must always be separated by spaces. |
expr 10 - 3 | Subtraction. |
expr 4 \* 5 | Multiplication. * must be backslash-escaped to prevent shell glob expansion. |
expr 10 / 3 | Integer division. The fractional part is truncated. |
expr 10 % 3 | Remainder (modulo). |
result=$(expr 1 + 2) | Combine with command substitution to assign the result to a variable. |
Arithmetic Expansion with $(( ))
$(( expr )) expands the result of an arithmetic expression as a string. It can be embedded directly wherever a value is needed, such as in arguments to echo or variable assignments. Where (( )) is for "evaluation (run for side effects)", $(( )) is for "expansion (extract a value)".
| Syntax | Description |
|---|---|
echo $((1 + 2)) | Passes the result of an arithmetic expression directly to echo and prints it. |
a=$((b + c)) | Assigns the result of an arithmetic expression to variable a. |
echo "Result: $((x * y))" | Arithmetic expansion can be embedded inside a string. |
$(( 2 ** 10 )) | Exponentiation (bash-specific). 2 ** 10 is 1024. |
$(( i % 2 )) | Remainder. Useful for odd/even checks. |
$(( 0xff )) | Hexadecimal literals are supported. 0xff is 255. |
$(( 010 )) | Octal literals are supported. 010 is 8. |
Sample Code
dragon_ball_power.sh
#!/bin/bash
# -----------------------------------------------
# A script that uses arithmetic operations to
# calculate the power levels of Dragon Ball characters
# -----------------------------------------------
# -----------------------------------------------
# 1. Basics of (( )) — evaluation and assignment
# -----------------------------------------------
# Set the base power level for each character
goku_power=9000
vegeta_power=8500
piccolo_power=3500
gohan_power=2800
krillin_power=1770
echo "=== Initial Power Levels ==="
echo "Goku: ${goku_power}"
echo "Vegeta: ${vegeta_power}"
echo "Piccolo: ${piccolo_power}"
echo "Gohan: ${gohan_power}"
echo "Krillin: ${krillin_power}"
echo ""
# Assign a calculated result to a variable using (( ))
(( total = goku_power + vegeta_power + piccolo_power + gohan_power + krillin_power ))
echo "Combined power of 5 fighters: ${total}"
# Conditional with (( )) — check if Goku's power exceeds 9000
if (( goku_power > 9000 )); then
echo "Goku's power level is over 9000!"
else
echo "Goku's power level is exactly 9000."
fi
echo ""
# -----------------------------------------------
# 2. Increment and decrement
# -----------------------------------------------
echo "=== Power-up through Training ==="
# Use postfix increment to advance Goku's training level
level=1
echo "Training level (start): ${level}"
(( level++ ))
echo "Training level (after +1): ${level}"
(( ++level ))
echo "Training level (after prefix ++): ${level}"
# Use compound assignment to increase power
(( goku_power += 1000 ))
echo "Goku's new power (+1000): ${goku_power}"
(( vegeta_power *= 2 ))
echo "Vegeta's new power (x2): ${vegeta_power}"
echo ""
# -----------------------------------------------
# 3. let — arithmetic evaluation command
# -----------------------------------------------
echo "=== Calculation with let ==="
# Use let to calculate the power difference between Vegeta and Goku
let "diff = vegeta_power - goku_power"
echo "Power difference between Vegeta and Goku: ${diff}"
# Use let to evaluate multiple expressions at once
let "piccolo_power += 500" "gohan_power += 200"
echo "Piccolo after training: ${piccolo_power}"
echo "Gohan after training: ${gohan_power}"
echo ""
# -----------------------------------------------
# 4. expr — arithmetic via external command
# -----------------------------------------------
echo "=== Calculation with expr ==="
# Addition with expr (spaces between operands are required)
result=$(expr ${krillin_power} + 230)
echo "Krillin's power after training: ${result}"
# Multiplication with expr (* must be escaped)
double=$(expr ${krillin_power} \* 2)
echo "Krillin's power doubled: ${double}"
# Modulo with expr
remainder=$(expr ${goku_power} % 1000)
echo "Goku's power mod 1000: ${remainder}"
echo ""
# -----------------------------------------------
# 5. $(( )) — arithmetic expansion
# -----------------------------------------------
echo "=== Output via Arithmetic Expansion ==="
# Embed arithmetic expansion inside a string
echo "Average power of Goku and Vegeta: $(( (goku_power + vegeta_power) / 2 ))"
# Exponentiation (2 to the power of 10)
echo "2 to the power of 10: $(( 2 ** 10 ))"
# Use modulo for odd/even check
for power in ${goku_power} ${vegeta_power} ${piccolo_power}; do
if (( power % 2 == 0 )); then
echo " ${power} -> even power level."
else
echo " ${power} -> odd power level."
fi
done
echo ""
# -----------------------------------------------
# 6. Arithmetic condition in a while loop
# -----------------------------------------------
echo "=== Goku's Training Count ==="
# Use (( )) as the while condition
count=1
while (( count <= 5 )); do
echo " Training session ${count}: power +$(( count * 100 ))"
(( count++ ))
done
echo ""
echo "=== Script complete ==="
chmod +x dragon_ball_power.sh ./dragon_ball_power.sh === Initial Power Levels === Goku: 9000 Vegeta: 8500 Piccolo: 3500 Gohan: 2800 Krillin: 1770 Combined power of 5 fighters: 25570 Goku's power level is exactly 9000. === Power-up through Training === Training level (start): 1 Training level (after +1): 2 Training level (after prefix ++): 3 Goku's new power (+1000): 10000 Vegeta's new power (x2): 17000 === Calculation with let === Power difference between Vegeta and Goku: 7000 Piccolo after training: 4000 Gohan after training: 3000 === Calculation with expr === Krillin's power after training: 2000 Krillin's power doubled: 3540 Goku's power mod 1000: 0 === Output via Arithmetic Expansion === Average power of Goku and Vegeta: 13500 2 to the power of 10: 1024 10000 -> even power level. 17000 -> even power level. 4000 -> even power level. === Goku's Training Count === Training session 1: power +100 Training session 2: power +200 Training session 3: power +300 Training session 4: power +400 Training session 5: power +500 === Script complete ===
Arithmetic Operator Reference
| Operator | Meaning | Example | Description |
|---|---|---|---|
+ | Addition | $(( 3 + 2 )) | Result is 5. |
- | Subtraction | $(( 5 - 2 )) | Result is 3. |
* | Multiplication | $(( 4 * 3 )) | Result is 12. |
/ | Division (truncated) | $(( 7 / 2 )) | Result is 3 (integer division). |
% | Modulo | $(( 7 % 2 )) | Result is 1. |
** | Exponentiation | $(( 2 ** 8 )) | Result is 256 (bash-specific). |
++ | Increment | (( i++ )) | Increases variable i by 1. |
-- | Decrement | (( i-- )) | Decreases variable i by 1. |
+= | Add and assign | (( i += 5 )) | Adds 5 to i and assigns. |
-= | Subtract and assign | (( i -= 3 )) | Subtracts 3 from i and assigns. |
*= | Multiply and assign | (( i *= 2 )) | Multiplies i by 2 and assigns. |
/= | Divide and assign | (( i /= 2 )) | Divides i by 2 and assigns. |
%= | Modulo and assign | (( i %= 3 )) | Assigns the remainder of i divided by 3. |
When to Use (( )) / let / expr / $(( ))
| Syntax | Type | Use case | sh compatible |
|---|---|---|---|
(( expr )) | bash built-in | For conditions and evaluations with side effects (e.g., increment). | No |
$(( expr )) | Arithmetic expansion | When a value is needed (assignment, embedding in echo, etc.). | Yes (POSIX) |
let | bash built-in | Alternative to (( )). Found in older scripts. Prefer (( )) for new scripts. | No |
expr | External command | When integer arithmetic is needed in a POSIX sh environment. In bash, prefer $(( )). | Yes |
Notes
Shell scripts offer four main ways to perform integer arithmetic. (( )) is bash's built-in arithmetic evaluation syntax with C-style operators (increment ++, decrement --, compound assignment +=, etc.). It can also be used as a condition in if (( expr )) and while (( expr )), enabling highly readable scripts. $(( expr )) is arithmetic expansion, used when you need to extract the result of an expression as a string. let is equivalent to (( )) but (( )) is the mainstream choice in modern scripts. expr is an external command that also works in POSIX sh, but its syntax can be verbose due to operator escaping requirements. In bash environments, it is best practice to standardize on $(( )) or (( )). See also Variables for information on declaring variables.
If you find any errors or copyright issues, please contact us.