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.

Advertisement

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 –

  1. var=$((var++))
    
  2. ((var++))
    
  3. let "i++"
    

Decrement operator expression in bash –

  1. var=$((var--))
    
  2. ((var--))
    
  3. 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.

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 variable j.
  • As it is post increment operation, then first original value will be assigned to variable j, then value of i will be increases by one.

Using while Loop:

Using for Loop:

Pre-Increment Example in Bash

The below example will use the pre increment operator.

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 variable j.
  • As it is pre increment operation, then first the value of the variable will be increases by 1 then the assignment will be performed.
Share.
Leave A Reply


Exit mobile version