29.2 C
New York

How to Increment and Decrement Variable in Bash (Counter)


Incrementing and decrementing variables are common operations in Bash scripting, especially when used as counters in loops. These operations involve adding or subtracting a value (typically 1) from a numeric variable. Bash provides several methods to perform these operations, including the use of operators, arithmetic expansion, and the let built-in command.

Using + and – Operators

The simplest way to increment or decrement a variable is by using the + and – operators:

let "i=i+1"

let "i=i-1"

These operations allow you to increment or decrement the variable by any desired value.

Here’s an example of incrementing a variable within an until loop:


until [ $i -gt 3 ]
  echo i: $i

The += and -= Operators

Bash also provides assignment operators, += and -=:

let "i+=1"

let "i-=1"

These operators increment or decrement the variable by the specified value.

In this example, we decrement the variable by 5 within a while loop:


while [ $i -ge 5 ]
  echo Number: $i
  let "i-=5"

Using ++ and — Operators

The ++ and -- operators increment and decrement the operand by 1:

let "i++"
let "++i"

let "i--"
let "--i"

These operators can be used in prefix or postfix form, with prefix operations returning the new value, and postfix operations returning the value before incrementing or decrementing.

Here’s an example demonstrating the use of postfix increment:

echo x: $x
echo y: $y

And an example of postfix increment in a script:

while true; do
  if [[ "$i" -gt 3 ]]; then
       exit 1
  echo i: $i

In conclusion, Bash provides various methods to increment and decrement variables. Choose the method that fits your specific needs and coding style.

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

Related articles

Recent articles