Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 95 ยท Shell Scripting

Arithmetic and Numbers

Do math in Bash with $(( )), (( )) and let: integer rules, floats with awk, number bases, bit operations, RANDOM, overflow and the classic octal trap.

A shell moves text around, so you might expect it to be bad at numbers. Bash is in fact quite capable at integer arithmetic: counters, loop indexes, sizes, offsets, exit codes, bit flags. It will not do decimals on its own, and it quietly wraps around when numbers get huge, but within those limits it is fast because the math happens inside the shell without starting another program.

In this lesson you will learn the three ways to calculate ($(( )), (( )) and let), how integer division and remainders behave, where to turn when you need decimals, how to work with hexadecimal, octal and binary, how to use bit operations for flags, and how to avoid the traps that catch almost everyone once (a leading zero, for example, makes a number octal).

Arithmetic expansion: $(( ))

The most common form is arithmetic expansion. Bash evaluates the expression between $(( and )) and replaces the whole thing with the result, as text:

Bash Arithmetic expansion basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Several rules are visible here:

  • Inside $(( )) you do not need $ in front of variable names. a + b works, and $a + $b works too. Leaving the $ out is the usual style and also avoids a subtle problem: with $x, the text is substituted before the math is parsed.
  • Spaces are optional, so you can format for readability.
  • Division truncates toward zero. 17 / 5 is 3, and -17 / 5 is -3 (not -4). The remainder takes the sign of the left operand: -17 % 5 is -2. The identity a / b * b + a % b == a always holds, which the "check" line proves.
  • Unset or non-numeric names count as 0. nothing and word are not defined, so both lines print 1. That is convenient for counters and dangerous for typos: a misspelled variable name silently becomes 0. Scripts that use set -u (see Exit Codes, set -e and Error Handling) turn that into an error, which is one reason to use it.
  • The usual C operators exist: + - * / % **, parentheses, comparisons (< <= > >= == !=), logic (&& || !), the ternary a ? b : c, and assignment forms. ** is exponentiation and associates right to left.

The result of $(( )) is just text, like any expansion. Quote it when it matters ("$((a + b))"), although digits never contain spaces, so an unquoted result is safe in practice.

Arithmetic commands: (( )) and let

Sometimes you do not want a value, you want to do something: add one to a counter, or test whether a number is large. The double-parenthesis arithmetic command (( ... )) evaluates an expression as a command. It has no $, so it prints nothing, but it can change variables and it sets an exit status:

  • The exit status is 0 (success) when the result is non-zero.
  • The exit status is 1 (failure) when the result is zero.

That is the opposite of C's idea of "true", but it matches the shell's: 0 means success. It makes (( )) ideal as the condition of an if or while (see Conditionals and Loops).

Bash The (( )) command and let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at what happened:

  • (( count++ )) and (( count += 5 )) modify count directly. The increment, decrement and compound assignments (+= -= *= /= %= <<= >>= &= ^= |=) all work.
  • i++ (post-increment) returns the old value, ++i returns the new one, exactly as in C.
  • Comparisons yield 1 for true and 0 for false inside the math, which (( )) then turns into exit status 0 or 1. So (( count == 0 )) fails and (( count )) succeeds.
  • The trap: (( zero = 0 )) has status 1 because the result of the expression is zero, even though nothing went wrong. Under set -e a bare (( count++ )) when count is 0 returns 1 and aborts the script. Use count=$((count + 1)) or (( ++count )), or add || true, when the value may be zero.
  • Commas separate several expressions, and (( )) returns the status of the last one.
  • let does the same job as (( )) using ordinary arguments, so expressions with spaces must be quoted: let "k = 3 * 4". (( )) is easier to read, and is what you should use.

Integers only, and what to do about decimals

Bash arithmetic uses signed integers and nothing else. 7 / 2 is 3. If a decimal sneaks in you get an error, not a rounded value. The usual tools for real numbers are awk (always available, see awk: Column Processing and Reports) and bc (a calculator program that is not installed in our sandbox, though it exists on most Linux servers). In scripts that must run everywhere, awk is the safest choice.

Bash Decimals with awk and fixed-point integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Four techniques are on display:

  1. awk does floating-point math. -v name=value passes shell values in safely. The format %.4f controls the digits.
  2. Fixed-point integers. Money is the classic case: store cents as integers, calculate with them, and only insert the decimal point when printing, as in total / 100 and total % 100. No rounding errors can creep in.
  3. printf can format a decimal that already exists as text (%.2f), but it does not calculate with it in Bash arithmetic. Notice that %5.1f shows 2.25 as 2.2: printf uses round-half-to-even on the binary value, not the school rule.
  4. Scale before dividing. To get a percentage without decimals, multiply first (7 * 100 / 9), because dividing first would throw the fraction away. To round to the nearest integer instead of truncating, add half the divisor before dividing, as in (700 + 4) / 9.

Mixing a decimal into $(( )) fails on purpose in the next example. The message tells you exactly where the parser gave up:

Bash A decimal inside arithmetic (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash reports 3.5: syntax error: invalid arithmetic operator (error token is ".5"). The 3 was read as a number, then the . was not a valid operator. The command that contained the expansion does not run, and the status is 1.

Number bases: binary, octal, decimal, hexadecimal

Inside arithmetic you can write a number in several bases:

Written as Meaning
255 Decimal
0xff or 0xFF Hexadecimal (base 16)
017 Octal (base 8): a leading zero!
2#1010 Base 2 (binary). The general form is base#digits, base 2 to 64
36#zz Base 36

Output is always decimal. To print another base use printf with %x (hex), %X, %o (octal) or a width such as %08d. For binary there is no %b number format in Bash, so write a small function (shown below).

Bit operations and flags

Bash has the full set of bitwise operators: & (and), | (or), ^ (xor), ~ (not), << and >> (shifts). They shine when you store several yes/no options in one number, the same idea behind Linux file permissions (see File Permissions and Ownership).

Bash Bases, printf and bit flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Reading the results:

  • 12 is 1100 in binary and 10 is 1010. AND keeps bits set in both (1000 = 8), OR keeps bits set in either (1110 = 14), XOR keeps bits set in exactly one (0110 = 6).
  • ~12 is -13: integers are stored in two's complement, so flipping every bit of a non-negative number gives -(n + 1).
  • 1 << n is the idiomatic way to define a flag: 1, 2, 4, 8, and so on. Testing is (( flags & FLAG )), setting is flags |= FLAG, clearing is flags &= ~FLAG, toggling is flags ^= FLAG.
  • printf '%d' "'A" (a quote before the character) prints its character code, 65.
  • The helper bin peels off the lowest bit with & 1 and shifts right until nothing is left. Functions are covered in Functions.

Random numbers, limits and overflow

$RANDOM gives a random integer from 0 to 32767. Assigning to it seeds the generator, which makes the sequence reproducible, handy for tests. To get a number in a range use the remainder: $(( RANDOM % 6 + 1 )) is a dice roll. (The remainder gives a very slightly uneven distribution because 32768 is not divisible by 6, which does not matter for games but does matter for security: never use $RANDOM for passwords or keys.)

Bash integers are 64-bit signed, so they range from -9223372036854775808 to 9223372036854775807. Go beyond that and the value silently wraps around. No error, no warning.

Bash RANDOM seeds and 64-bit wrap-around

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Seeding with 42 twice gives the same three numbers both times (17766 11151 23481 in this Bash). The exact numbers belong to this Bash version, so tests should compare behaviour, not specific values. Factorial 20 is the last one that fits; 21! wraps to a negative number. For really large numbers use awk (which loses precision instead) or a language with big integers.

Traps and a safer way to declare numbers

The most famous trap is the leading zero. A number starting with 0 is octal, so 08 and 09 are errors, and 010 is 8. This bites when you read months, days or hours from date or a file, which are zero-padded. Force decimal with the 10# prefix.

Bash A leading zero is octal (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first line prints ok with 10#: 9. The second fails with 08: value too great for base (error token is "08"), because 8 is not a valid octal digit. Dividing by zero is also an error: $((10 / 0)) prints division by 0 (error token is "0") and the command does not run.

Another trap is string math. A plain assignment never calculates; s=5+3 stores the five characters. Declaring a variable as an integer with declare -i changes that: every later assignment is evaluated as arithmetic. And remember that [[ 10 > 9 ]] compares strings (the character 1 sorts before 9), whereas (( 10 > 9 )) and [[ 10 -gt 9 ]] compare numbers. More on that in Conditionals: if, test and [[ ]].

Bash declare -i and string versus number comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Notice echo "$x+$y" prints 5+3: without $(( )) it is only text.

$(( and (( are Bash features (also in ksh and zsh), and $(( )) is in POSIX sh, but (( )), let, **, declare -i and RANDOM are not guaranteed in sh. With a #!/bin/sh script, use $(( )) and stay away from the rest. See POSIX sh, Portability and Compatibility.

When to use what

  • Counters, indexes, sizes, flags: $(( )) and (( )). They are fast, built in, and need no extra process.
  • Decimals, percentages with fractions, roots, logs: awk (or bc where installed).
  • Money: integer cents, formatted with printf.
  • Anything beyond 64 bits or needing exactness with decimals: leave Bash.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does echo $((-17 / 5)) print in Bash?

    Integer division truncates toward zero, so -17 / 5 is -3. There are no decimals in Bash arithmetic, and the sign is kept.
  2. 2. Under set -e, why can a bare (( count++ )) stop a script when count is 0?

    Post-increment returns the old value, 0, and (( )) reports failure (status 1) when its result is zero. Use ++count, count=$((count + 1)) or add || true.
  3. 3. What happens with n=08; echo $((n + 1))?

    A leading 0 means octal. Use $((10#$n + 1)) to force decimal.
  4. 4. Which is the best way to compute 7 divided by 2 as 3.500 in a script?

    Bash arithmetic is integer only. awk does floating-point math and printf formats the result.
  5. 5. What does $((9223372036854775807 + 1)) print?

    Bash uses 64-bit signed integers and silently wraps around on overflow, so the largest value plus one becomes the smallest.

Summary

  • $(( expr )) yields a value; (( expr )) is a command that changes variables and returns status 0 for a non-zero result and 1 for zero. let is the older equivalent.
  • Arithmetic is integer only, 64-bit signed, with C operators including **, the ternary ?: and ++/+=. Division truncates toward zero.
  • Unset names count as 0; set -u catches typos.
  • Use awk for decimals, integer cents for money, and multiply before dividing for percentages.
  • Write numbers as 0x1f, 2#1010, or base#digits; a leading zero means octal, so use 10# for zero-padded input.
  • Bitwise operators (& | ^ ~ << >>) with 1 << n give flag sets: test with &, set with |=, clear with &= ~.
  • RANDOM=seed makes $RANDOM repeatable; values wrap silently past 64 bits.
  • declare -i makes assignments arithmetic; [[ a > b ]] compares strings, (( a > b )) compares numbers.

Next: Conditionals: if, test and [[ ]]