How to Increment and Decrement Variable in Bash (Counter)

One of the most common arithmetic operations when writing Bash scripts is incrementing and decrementing variables. This is most often used in loops as a counter, but it can occur elsewhere in the script as well.

Incrementing and Decrementing means adding or subtracting a value (usually 1), respectively, from the value of a numeric variable. The arithmetic expansion can be performed using the double parentheses ((...)) and $((...)) or with the let built-in command.

In Bash, there are multiple ways to increment/decrement a variable. This article explains some of them.

Using + and - Operators

The most simple way to increment/decrement a variable is by using the + and - operators.

i=$((i+1))
((i=i+1))
let "i=i+1"

Copy

i=$((i-1))
((i=i-1))
let "i=i-1"

Copy

This method allows you increment/decrement the variable by any value you want.

Here is an example of incrementing a variable within an [until](https://linuxize.com/post/bash-until-loop/) loop

``` i=0

until [ $i -gt 3 ]
do
echo i: $i
((i=i+1))
done


<span style="background-color: rgba(203,213,224,var(--bg-opacity));">Copy</span>

i: 0
i: 1
i: 2
i: 3

#bash #counter

How to Increment and Decrement Variable in Bash (Counter)
23.35 GEEK