05. Arithmetic expansions and tests

Arithmetic expansions

There are two ways we can have the shell evaluate an expression. Either using $((expression)) syntax or the expr command.

The former does not require proper spacing, while the latter does.

$ echo $((2+3))
5
$ expr 2 + 3
5

Arithmetic expasion only supports integer values and no decimals.

$ expr 2.3 + 2
expr: not a decimal number: '2.3'

Operators

Here are a list of arithmetic operators.

++ --
Increment, Decrement
+ -
Unary plus and minus
* / %
Multiplication, division and remainder
== !=
Equal and not equal
! && ||
Logical negation, AND, and OR
<< >>
Bit-shift left and right
~ & ^ |
Bitwise negation, AND, exclusive OR, and OR
\= += -= *= /= %=
Assignment operators
&= ^- <<= >>= |=
Bitwise assignment operators

Arithmetic test

It's important to avoid using the = symbol when comparing numerals. The = looks for string equality, not numeric equality. Thus, when working with arithmetic equations, be sure to use -eq instead.

$ [ 1 = 1 ]; echo $?
0
$ [ 092 = 92 ]; echo $?
1
$ [ 092 -eq 92 ]; echo $?
0

Here is a list of more comparison tests we can use to compare two numbers. Be sure to not use canonical notations such as > or <!

-eq
Equal to
-ne
Not equal to
-lt
Less than
-gt
Greater than
-le
Less than or equal to
-ge
Greater than or equal to
$ [ 92 > 32 ]; echo $?
0      # Looks good...(but wrong)
$ [ 92 < 32 ]; echo $?
0      # Wrong
$ [ 92 -gt 32 ]; echo $?
0      # There we go!

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

Linux for Beginners

Take your Linux skills to the next level! Try Linux & UNIX

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Ad