Search⌘ K

The (( Operator

Explore how to perform integer arithmetic in Bash using the (( operator, including its forms for arithmetic evaluation and expansion. Understand how it simplifies expressions, avoids common errors, and how it differs from the let command for clearer, more reliable Bash scripts.

We'll cover the following...

Bash performs integer arithmetic in math context.

The syntax of math context resembles the C language. The idea behind it is to make Bash easier to learn for programmers who have experience with the C language. Most users of the first Unix versions knew C.

Let’s suppose we want to store a result of adding two numbers in a variable. We need to declare it using the -i attribute and assign a value in the declaration. Here is an example:

declare -i var=12+7

Run the commands discussed in this lesson in the terminal below.

Terminal 1
Terminal
Loading...

When processing this declaration, the variable gets the value 19 instead of the “12+7” string. This happens because the -i attribute forces Bash to apply the mathematical context when handling the variable.

The let command

There is an option to apply the mathematical context besides the variable declaration. We call the let built-in command to accomplish that.

Let’s suppose that we declare the variable without the -i attribute. Then, the let built-in allows us to calculate an ...