Site icon DesignLinux

How to Increment and Decrement Variable in Bash

Increment & Decrement a Variable in Bash

Variable increment and decrement is fundamental arithmetic operation in bash scripting. It’s mostly used with the for, while and until loops. Increment means adding value to variable and Decrement means subtracting from numeric variable value. This article explains multiple ways to increment or decrement a variable.

Use of + and - Operators

You must use the double parentheses ((…)) and $((…)) to perform the arithmetic expansion. Use the + and - operators to increment or decrement the variable.

a=$((a+1))
((a=a+1))
let "a=a+1"
a=$((a-1))
((a=a-1))
let "a=a-1"

You can increment or decrement by any value whatever you want. Let’s see an example with the until loop:

a=0

until [ $a -gt 5 ]
do
  echo a value is : $a
  ((a=a+1))
done
a value is : 0
a value is : 1
a value is : 2
a value is : 3
a value is : 4

The += and -= Operators

The += and -= are the assignment operators. You also can use the assignment operators to increment or decrement the value of the left operand with the value which given after the operator.

((a+=1))
let "a+=1" 
((a-=1))
let "a-=1" 

For instance, we will increment the value of variable a by 2:

a=0

while [ $a -ge 5 ]
do
  echo a value is: $a
  let "a+=2" 
done
a value is : 0
a value is : 2
a value is : 4
a value is : 6
a value is : 8

Using the ++ and -- Operators

The ++ operator will increment and -- operators will decrement operand value by 1 and will return the value. These operator are also know as prefix and postfix increment and decrement operators.

((a++))
((++a))
let "a++"
let "++a"
((a--))
((--a))
let "a--"
let "--a"

These operators can be used before or after the operand. The prefix operators first increment or decrement the value of operand by 1 and return the new value. While the postfix operators first returns the operand value and then increment or decrement the value.

To understand properly let’s see an example how the ++ operator works:

a=5
b=$((a++))
echo a: $a
echo b: $b
a: 6
b: 5
a=5
b=$((++a))
echo a: $a
echo b: $b
a: 6
b: 6

Following is the example of how to use the postfix incrementor in a bash script:

#!/bin/bash
a=0
while true; do
  if [[ "$a" -gt 5 ]]; then
       exit 1
  fi
  echo a: $a
  ((a++))
done

This is most used operator while need to increment by 1. The limitation of this operator is that it can be used only when need to increment or decrement value by 1. You can not increment more than 1 using these operators.

Conclusion

In this article, we have explained multiple ways to use the increment and decrement operators in bash script.

If you have any questions or feedback, feel free to leave a comment.

Exit mobile version