How To Increment Variable In Bash Shell and Script?

Linux Bash Shell is a complete shell with programming features. The bash shell provides variables and arithmetic operations like sum, divide, etc. The bash shell variables can be incremented in different ways. This incrementation operation can be done in different ways. In this tutorial, we will learn different ways to increment or increase a variable in bash.

Increment Bash Variable with + Operator

Most of the programming languages provide the + operator in sum two or more integers or numbers. The bash also supports the + operator which can be used to increment a variable. The bash variable can be incremented by summing it with the 1. By default, the + operator has a different meaning than the sum for the bash shell. The $((…)) operators are used to express the + operator is used arithmetic operation.

i=12

echo $i

i=$((i+1))

echo $i

The output is like below.

12
13

Increment Bash Variable with += Operator

Another common operator which can be used to increment a bash variable is the += operator. This operator is a short form for the sum operator. The first operand and the result variable name are the same and assigned with a single statement.

i=12

echo $i

((i+=1))

echo $i

Increment Bash Variable with ++ Operator

The ++ operator is the most practical operator which can be used the increment a bash variable with a single statement. There is no need to specify the increment value or anything else. The ++ operator can be directly used with the variable. There is two way to use ++ operator.

  • ++i version is called prefix and the variable value is incremented one before the usage of the variable.
  • i++ version is called postfix and the variable value is incremented one after the usage of the variable.

Lets make some example to understand the prefix and postfix ++ operator.

i=12

echo $i

echo $((i++))

echo $i

echo $((++i))

echo $i

((i++))

echo $i

The output is like below.

12
12
13
14
14
15

Leave a Comment