We're an ISO27001:2013 Certified Supplier

maths

Whilst there are far more suitable scripting languages than bash when it comes to maths, it can be useful to understand what can be done in bash. Let’s look at our options.

Integer Maths

The first point to appreciate is that all maths in bash is with integers: no floating point or similar, and no check for overflow. Maths operations take place inside the compound command double parentheses:

$ echo $((6+7)) 
13

The usual maths operators are supported:

$ a=10
$ echo $((a+3))
13
$ echo $((a-3))  # addition
7
$ echo $((a*3))  # subtraction
30
$ echo $((a/3))  # integer division
3
$ echo $((a%3))  # remainder
1

Comparison:

$ [[ $a<100 ]] && echo "a is less than one hundred"
a is less than one hundred
$ [[ $a>100 ]] && echo "a is more than one hundred"
$

Increment and Decrement

C-style increment and decrement operators are supported, but note that with post- increment the expression is evaluated before the increment takes place:

$ a=17
$ b=$((a++)
$ echo $b
17
$ echo $a
18

Compare with pre-increment:

$ a=12 
$ b=$((++a)) 
$ echo $b, $a 
13, 13

Bitwise

If you need to do bitwise operations, don’t use bash– really, there are better tools. If you must:

$ echo $((8>>1))
4
$ echo $((8<<1))
16
$ echo $((12>>2))
3

Random

Generate a random number between 0 and 32767 :

$ echo $RANDOM
7314

Generate a random number between 0 and 100:

$ echo $((RANDOM%101))
63

Comparison

Use -eq (equal), -ne (not equal), -lt (less than), -le (less than or equal), -gt (greater than), or -ge (greater than or equal):

$ a=7
$ [ $a -lt 10 ] && echo "a is less than ten"
a is less than ten

Don’t confuse them with the similar =, !=, < and > operators, which operate on strings, not integers:

# Numerically, 20 is less than 100:
$ [[ 20 -lt 100 ]] && echo "20 is less than 100"
20 is less than 100

# Lexically, 20 is not less than 100:
$ [[ 20 < 100 ]] && echo "20 is less than 100"

It’s possibly confusing that the arithmetic comparison operators are strings (-lt, -gt) and the lexical comparison operators are arithmetic symbols (<, >).

Not Ideal

If you want to anything more than the smallest, simplest maths then use Python or Perl or some other tool. When it’s needed, bash can handle a little simple maths.

Was This Linux Tip Useful?

Let us know in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Secure. Reliable. Scalable.

If that doesn't describe your current Linux systems, check out our FREE Linux Survival Guide to help you get your systems up to scratch today!

  • This field is for validation purposes and should be left unchanged.