Incrementing or decrementing variables is a fundamental but essential part of writing code or, for that matter, scripts. The operation generally refers to increasing or decreasing the value of a variable by one.
In this article, we’re going over how you can increment (or decrement) a variable in Bash.
Arithmetic operations in Bash
Before we get to make changes to our variables, here’s a little something on arithmetic operations in Bash. To perform them, you’re either going to have to enclose the required variables in double parenthesis written as ((…)) or $((…)). You can use the keyword let as well.
Now, as far as incrementing a variable is concerned, you can do this in several ways. We’ll be going over all three of these methods.
Also read: How to concatenate strings in Bash?
How to increment a variable in Bash using the + or – operators?
This is the easiest method and works exactly how you’d expect it to work. You declare a variable, and every time you need to increment or decrement it, you add or subtract one.
i = $((i+1))
((i=i+1))
let "i=i+1"
Here’s an example of this approach being used in a loop that increases the value of a variable until it reaches three.
i=0
until [ $i -gt 3 ]
do
echo i: $i
((i=i+1))
done
Also read: Bash While loop explained
How to increment a variable in Bash using the += or -= operators?
These operators are basically shorthand for addition or subtraction. They can add (or subtract) the value of the left operand with the value specified after the operator.
((i+=1))
let "i+=1"
Here’s an example of this approach being used in a loop that increases the value of a variable until it reaches three.
i=0
until [ $i -gt 3 ]
do
echo i: $i
((i+=1))
done
Also read: Bashrc vs Bash_profile
How to increment a variable in Bash using the ++ or — operators?
Once again, these operators are shorthand for addition or subtraction, except they only add or subtract one from a single operand specified on the left. This is one of the most popular ways you’ll come across for incrementing/decrementing in a script or code, regardless of the programming language used.
((i++))
let "i++"
Note that the position of the variable with respect to the operators can affect the output here. For example, if you write ((++i)), the value of i will first be incremented and then interpreted. Meaning if it were originally 3, it’d now be interpreted as 4.
On the flip side, if you write ((i++)), the value of i will first be interpreted and then incremented. Meaning that the script will use the existing value of i and then increment the variable. These operators are most commonly used in the for loops.
Here’s an example of this approach being used in a loop that increases the value of a variable until it reaches three.
#!/bin/bash
i=0
while true; do
if [[ "$i" -gt 3 ]]; then
exit 1
fi
echo i: $i
((i++))
done
Also read: Bash command not found: 3 Fixes