Math with the shell
Arithmetic operations are an essential requirement for every programming language. In this recipe, we will explore various methods for performing arithmetic operations in shell.
Getting ready
The Bash shell environment can perform basic arithmetic operations using the commands let
, (( ))
, and []
. The two utilities expr
and bc
are also very helpful in performing advanced operations.
How to do it...
- A numeric value can be assigned as a regular variable assignment, which is stored as a string. However, we use methods to manipulate as numbers:
#!/bin/bash no1=4; no2=5;
- The
let
command can be used to perform basic operations directly. While usinglet
, we use variable names without the$
prefix, for example:let result=no1+no2 echo $result ...
Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.