Bash Scripting: Arithmetic operations - JohnHau/mis GitHub Wiki

he need to perform basic arithmetic operations is common in all types of programming, including in Bash scripts. A Linux system has multiple ways to perform arithmetic operations, and it is up to the user to decide the best method for the scenario at hand.

In this tutorial, you will learn several ways to use arithmetic operations to perform basic calculations inside of a Bash script on Linux. Check out the examples below to see how these different methods work.

In this tutorial you will learn:

How to use arithmetic operations with double parentheses, bc, let, expr, and awk in a Bash script

image

Bash Scripting: Arithmetic operations examples The methods covered below are double parentheses (( )), basic calculator bc, let, expr, and awk commands. All should do the job, so use whichever one makes the most sense for your scripting environment.

Double parentheses While the other methods rely on a command to perform an arithmetic operation, the double parentheses method is integrated in the Bash shell and is a great choice for performing calculations with numbers and/or variables inside of a Bash script. Let’s look at an example below to see different ways this method can be used.

image

image

image

Let command

image

image

image image

image