Skip to the workspace
Pebellslearn by building
Variables and Data  ›  Lesson

Numbers and Arithmetic Expansion

Numeric 12 minBash supports integer arithmetic through constructs such as arithmetic expansion, arithmetic commands and integer variables. Decimal calculations normally require another tool.

shell bash / Numbers and Arithmetic Expansion

Explore each scene at your own pace.

01 · The rule

The rule

Numbers and Arithmetic Expansion

Bash supports integer arithmetic through constructs such as arithmetic expansion, arithmetic commands and integer variables. Decimal calculations normally require another tool.

Perform integer arithmetic and recognize when an external decimal tool is needed.

backup.sh should keep archives for 30 days and report that as weeks. You write weeks=$keep_days/7, echo it, and Bash proudly prints 30/7. Since every value is text, Bash needs a signal before it will do maths.

The rule

Maths lives inside $(( )), and Bash counts only whole numbers.

$(( expression )) evaluates the expression and puts the result in its place. Inside the double parentheses you can drop the $ from variable names and use spaces freely:

keep_days=30
weeks=$(( keep_days / 7 ))      # 4
spare=$(( keep_days % 7 ))      # 2
echo "Keeping $weeks weeks and $spare days"

The operators are the familiar ones: + - * /, % for remainder, ** for power. Division throws away the remainder: 7 / 2 is 3.

Close relatives:

  • (( ... )) without the $ runs arithmetic for its effect, such as (( count++ )) or (( total += size )). Its exit status is success when the result is non-zero, which makes it handy in if.
  • let count=count+1 is an older spelling of the same idea.
  • expr 7 + 2 is an old external program; you will see it in old scripts, but $(( )) is faster and clearer.

For decimals, hand the sum to a calculator program such as bc:

echo "scale=2; 30 / 7" | bc      # 4.28
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.