Have you ever performed any arithmetic calculation in Bash? If you’re new to Bash scripting, you might encounter difficulties when it comes to performing arithmetic operations. In this article, I’ll demonstrate the syntax and guide you on where and how to write arithmetic expressions to ensure accurate calculation. Along with this arithmetic expansion for calculation I will show you a few commands that can effectively perform arithmetic calculation in Bash.

**Table of Contents**Expand

### Key Takeaways

- Learning about arithmetic expansion.
- Understanding the operators for different arithmetic operations.
- Arithmetic expansion alternatives in Bash.

### Free Downloads

### Syntax of Arithmetic Expansion

The structure of arithmetic expansion in Bash is “**$((…))**”. Inside the double parentheses, one can put mathematical **expressions**, **variables** and **operators**. The shell will evaluate the expression and replace the “**$((…))**” construct with the result of the calculation. Let’s calculate the sum of **4** and **5 **in the terminal.

`echo $((4 + 5))`

The image shows the addition of **4** and **5** inside the “**$((…))**”. Then it prints the evaluated result **9** using the **echo command**.

## 3 Practical Applications of Arithmetic Expansion in Bash

There are many applications of arithmetic expansion in **Bash** **scripting**. In this article, I’d like to highlight three fundamental use cases of arithmetic expansion, which encompass scenarios such as **multiplication** and **bitwise operations **and others.

### Application 01: Multiplication of Two Integer Numbers in Bash

In this demonstration, I want to show how to multiply two numbers in **Bash**. In case of arithmetic expansion the numbers to be multiplied should be integer type. Floating point numbers can’t be multiplied in this way.

- At first, launch an
**Ubuntu****Terminal**. - Write the following command to open a
**multiply.sh**file in the built-in**nano**editor:`nano multiply.sh`

EXPLANATION**nano**: Opens a file in the Nano text editor.**multiply.sh**: Name of the file.

- Now,
**write the following script**inside the editor:**Script (multiply.sh) >**`#!/bin/bash # Prompt the user to enter the first number read -p "Enter the first integer: " num1 # Prompt the user to enter the second number read -p "Enter the second integer: " num2 # Perform the multiplication result=$((num1 * num2)) # Display the result echo "The product of $num1 and $num2 is $result"`

EXPLANATION“

**#!/bin/bash**” is called “**shebang**” that specifies the**Bash**interpreter. The script begins by prompting the user to input two integer values. It uses the**read**command to capture these inputs.After collecting the user’s input, it performs the multiplication of these two integer values using arithmetic “

*****” operator. Finally, the script displays a message indicating the product of the two input numbers utilizing the**echo command**. - Use the following command to
**make the file executable**:`chmod u+x multiply.sh`

EXPLANATION**chmod**: Changes permissions.**u+x**: Giving the owner executing permission.**multiply.sh**: Name of the script.

**Run the script**by the following command:`./multiply.sh`

Once executed the program takes two integer input from the user and calculate their product. In the above execution user gives

**4**and**5**and the program returns**20**as their product.

#### Arithmetic Operators

Apart from **multiplication** operator, there are other arithmetic operators. The below list contains all the arithmetic operators for basic calculation.

Operator |
Description |
Example |
---|---|---|

Addition (+) |
Adds two numbers together. | $((5 + 3)) is 8 |

Subtraction (-) |
Subtracts the right operand from the left operand. | $((10 – 3)) is 7 |

Multiplication (*) |
Multiplies two numbers. | $((4 * 6)) is 24 |

Division (/) |
Divides the left operand by the right operand. | $((10 / 3)) is 3 |

Modulus (%) |
Computes the remainder when the left operand is divided by the right operand. | $((10 % 3)) is 1 |

### Application 02: Bash Script for Checking Odd or Even Number

One can easily check even or odd numbers in Bash using the **remainder **or **modulus **(“**%**”) operator. The following script shows how to determine whether a number is odd or even.

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (oddeven.sh) >**

```
#!/bin/bash
# Bash script to check if a number is even or odd
read -p "Enter the number: " number
check=$((number % 2))
if [ $check -eq 0 ]; then
echo "The number is even."
else
echo "The number is odd."
fi
```

This Bash script allows the user to input a number, which is stored in the **number** variable using the **read **command. It then calculates the **remainder **when the **number** is divided by **2** using the ‘**%**‘ operator. If the **remainder** is **0**, the script prints “**The number is even.**” Conversely, if the **remainder** is not **0**, it prints “**The number is odd.**“

Run the script using the following command:

`./oddeven.sh`

It is evident that remainder can be easily calculated by ‘**%**‘ operator. But what happens if there are multiple operators in a single calculation? Let’s talk about precedence rule in **Bash**.

#### Precedence Rules

Bash follows standard arithmetic operator precedence rule. One can use parentheses to explicitly specify the order of operations. But if not specified, it performs **Exponents**, **Multiplication**, **Division**, **Addition** and **Subtraction **consecutively.

`echo $((2 ** 3 / 4))`

In this calculation, arithmetic expansion first computes **2^4**, which equals **16**. Then, it divides the result by **2**, yielding a final answer of **8**.

Can you imagine what happens if you put one arithmetic expansion inside another? Let’s explore the nested feature of arithmetic expansion.

#### Nested Expansion

The arithmetic expansion also works in a nested fashion. It means you can expand an arithmetic calculation inside another calculation.

`echo $((2 * $(( 4 + 6))))`

As you can see, in the above code “**$(( 4 + 6))**” expands inside another arithmetic expansion.

### Application 03: Bitwise “AND” Operation in Bash

Bash can handle **bitwise** calculation using arithmetic expansion. In this application, I want to show “**bitwise AND**” operation “**&**” operator.

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (bitwise.sh) >**

```
#!/bin/bash
# Define two decimal numbers
num1=10
num2=6
# Perform bitwise AND operation
result=$((num1 & num2))
# Print the result
echo "Result of $num1 & $num2 is $result"
```

The above script defines two decimal numbers, **num1** and **num2**, as **10** and **6**, respectively. It then performs a **bitwise AND** operation between these numbers using the “**&**” operator and stores the result in a variable.

The script then displays the result of **bitwise AND **operation using the **echo** command.

Run the script using the following command:

`./bitwise.sh`

In this **bitwise AND** operation, the binary representations of **10** and **6** are **1010** and **0110** respectively. Their bitwise **AND** results in **0010**, which is **2** in decimal.

## Floating Point Arithmetic in Bash

The arithmetic expansion in **Bash **is originally designed for working with integers. It can’t perform arithmetic calculations of floating point numbers. Fortunately, there are other commands like the **bc** **command** that can perform calculations with floating point numbers. Let’s add two floating point numbers using the **bc **command.

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (float.sh) >**

```
#!/bin/bash
# Define floating-point numbers
num1=3.14
num2=2.5
# Perform floating-point addition using bc command
result=$(echo "$num1 + $num2" | bc -l)
# Print the result
echo "Sum of $num1 + $num2 is $result"
```

This Bash script aims to add two floating-point numbers, **num1** and **num2**, with values **3.14 **and **2.5**, respectively.

The **echo** command is used to construct the expression for addition. Then it utilizes the **bc** command and piped the expression into **bc -l**. Here, **-l **option specifies “**long**” mode for handling floating-point arithmetic.

Run the script using the following command:

`./float.sh`

The program computes the addition of **3.14** and **2.5**. Result **5.64 **is displayed in the **terminal**.

**NOTE:**The

**bc command**can also perform integer arithmetic.

## Alternatives of Arithmetic Expansion in Bash

**Arithmetic expansion** is designed to perform integer arithmetic in Bash. However, there are many other alternatives to it. As I already discussed the **bc** command, there are few other commands such as the **let** command, **expr** command and **awk command** that can be employed to perform arithmetic calculation in place of **arithmetic expansion**. Let’s see some examples of each of these commands.

### Example 01: Utilizing the “expr” Command for Arithmetic Calculation in Bash

To perform arithmetic calculation using the **expr** command, write the expression after the word “**expr**”. But never forget to enclose the whole expression with **dollar sign**. The whole syntax should be something like this- “**$(expr expression)**”

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (expr.sh) >**

```
#!/bin/bash
# Prompt the user to enter the first number
read -p "Enter the first number: " num1
# Prompt the user to enter the second number
read -p "Enter the second number: " num2
sub_result=$(expr $num1 - $num2)
echo "Subtraction Result: $sub_result"
```

The script uses the **read** command with the **-p** option to take input in the **num1** and **num2** variables, respectively. Subsequently, it utilizes the **expr** command to perform subtraction between **num1** and **num2**.

The result is stored in the **sub_result **variable. Finally, it employs the **echo** command to display the subtraction result.

Run the script using the following command:

`./expr.sh`

The image shows that the **expr **command successfully subtracts **5 **from **10**.

### Example 02: Employing the “awk” Command for Arithmetic Calculation

The **awk** command is mainly used for text processing and data manipulation. However, it can be used for arithmetic calculation as well. In this demonstration I will show you how to add two numbers using the **awk **command.

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (awk.sh) >**

```
#!/bin/bash
# Prompt the user to enter the first number
read -p "Enter the first number: " num1
# Prompt the user to enter the second number
read -p "Enter the second number: " num2
# Use awk to perform the addition and store the result in the 'result' variable
result=$(awk -v n1="$num1" -v n2="$num2" 'BEGIN {print n1 + n2}')
# Print the result
echo "Result: $result"
```

This Bash script prompts the user to input two numbers, **num1** and **num2** using the **read** command. It then employs the **awk** command with the **-v** option to pass these numbers as variables **n1** and **n2**.

Within an awk **BEGIN** block, it calculates the sum of **n1** and **n2** and displays the result using the **echo** command.

Run the script using the following command:

`./awk.sh`

The image shows that the program calculates the summation of **10** and **15 **and displays the result.

### Example 03: Using the “let” Command for Arithmetic Calculation in Bash

The **let** command is another very good alternative to arithmetic expansion. It evaluates arithmetic expressions without any syntax complexity. Let’s increment a variable by one using the **let **command.

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (let.sh) >**

```
#!/bin/bash
read -p "Enter the number: " num
let "num=num+1"
echo "Result: $num"
```

This Bash script prompts the user to enter a number, which is stored in the **num **variable. Then it utilizes the **let** command to increment the value of **num** by **1**. Finally, it echoes the incremented value of **num **using the **echo** command.

Run the script using the following command:

`./let.sh`

As the image shows, the **let **command adds **1 **with the user input **5**. After addition, it shows the result **6 **in the **terminal**.

## How Arithmetic Evaluation Differs from Arithmetic Expansion

Arithmetic evaluation differs from arithmetic expansion in Bash. “**$[ expression ]**” or “**(( expression ))**” syntax can evaluate the expression inside it. However, these constructs don’t store the result of evaluation, rather it compares the calculated value with a predefined threshold. This is particularly useful for control structures in **Bash**. Look at the script below to see how arithmetic evaluation is used in control structures of Bash script.

**Steps of Application 01**to learn about creating and saving shell scripts.

**Script (arr_eval.sh) >**

```
#!/bin/bash
# Bash script to check if a number is even or odd
read -p "Enter the number:" number
if ((number % 2 == 0)); then
echo "The number is even."
else
echo "The number is odd."
fi
```

This Bash script allows the user to input a number, which is stored in the **number** variable using the **read **command. It then calculates the **remainder **when the **number** is divided by **2** using the ‘**%**‘ operator. If the **remainder** is **0**, the script prints “**The number is even.**” Conversely, if the **remainder** is not **0**, it prints “**The number is odd.**“

Run the script using the following command:

`./arr_eval.sh`

The program works perfectly as it determines **5 **as an odd number. Within the **if structure** the program divides the “**number**” by **two** and compares it with **zero **using “**((number % 2 == 0))**” construction. This certainly differs from **arithmetic expansion** that have double parenthesis followed by a **dollar sign**.

## Conclusion

In conclusion, arithmetic expansion is essential for any kind of arithmetic calculation in Bash. I believe that after reading this article, you have a clear understanding of arithmetic expansion in Bash scripting. Furthermore, I have attempted to provide you with information about alternative commands for arithmetic calculations in Bash. Hope you have enjoyed reading the text.