Similar to other programming language bash also supports increment and decrement operators. The increment operator ++
increases the value of a variable by one. Similarly, the decrement operator --
decreases the value of a variable by one.
Pre and Post Increment:
- When using
++
operator as prefix like:++var
. Then first the value of variable is incremented by 1 then, it returns the value. - When using the
++
operator as postfix like:var++
. Then first original value will returned and after that the value incremented by 1.
Pre and Post Decrement:
- When using
--
operator as prefix like:--var
. Then first the value of variable is decremented by 1 then, it returns the value. - When using the
--
operator as postfix like:var--
. Then first original value will returned and after that value is decremented by 1.
Using ++
and --
Operators in Bash
In bash scripting, increment and decrement operators can be write in various ways. You can choose any of the below expression defined below to perform post increment or decrement value in bash.
Increment operator expression in bash –
var=$((var++))
((var++))
let "i++"
Decrement operator expression in bash –
var=$((var--))
((var--))
let "i--"
Post-Increment Example in Bash
Below is the sample example of increment operator, where we assigning a numeric value to a variable (i). Then Perform the post increment (i++) operation on variable and with storing value to another variable.
1 2 3 4 | i=10 j=$((i++)) echo $j echo $i |
Output:
10 11
See the above results and understand what happened.
- In first row, we assigned number value 10 to variable
i
. - Then perform post increment (
i++
) and assign value to variablej
. - As it is post increment operation, then first original value will be assigned to variable
j
, then value ofi
will be increases by one.
Using while Loop:
1 2 3 4 5 6 | i=1 while(($i<10)) do echo $i ((i++)) done |
Using for Loop:
1 2 3 4 | for((i=1; i<10; i++)) do echo $i done |
Pre-Increment Example in Bash
The below example will use the pre increment operator.
1 2 3 4 | i=10 j=$((++i)) echo $j echo $i |
Output:
11 11
See the above results and understand what happened.
- In first row, we assigned number value 10 to variable
i
. - Then perform pre increment (
++i
) and assign value to variablej
. - As it is pre increment operation, then first the value of the variable will be increases by 1 then the assignment will be performed.