Incrementing And Decrementing In Bash With Prefix And Postfix Operators

Pavol Kutaj
2 min readDec 15, 2021

--

The aim of this pageđź“ť is to show the 3 ways of incrementing and decrementing a number in bash. Basically notes from How to Increment and Decrement Variable in Bash (Counter) | Linuxize.

I used the third option in the C-style loop needed for writing a shell script implementing a wrapper around Snowplow Analytics CLI (called via track_script a function that looked something like) that fired as many events as passed from the shell.

request_count=$1
for ((i = 1; i <= request_count; i++)); do
echo "request #${i}:"
track_script "$job_tag" "STARTING" "$cluster_type" "$band" "$size_kb"
done

1. + and -

  • The most simple way to increment/decrement a variable is by using the + and — operators.
i=$((i+1))
((i=i+1))
let "i=i+1"
i=$((i-1))
((i=i-1))
let "i=i-1"
  • This method allows you to increment/decrement the variable by any value you want. Here is an example of incrementing a variable within an until loop:
i=0

until [ $i -gt 3 ]
do
echo i: $i
((i=i+1))
done
i: 0
i: 1
i: 2
i: 3

2. += and -=

  • In addition to the basic operators explained above, bash also provides the assignment operators += and -=
  • These operators are used to increment/decrement the value of the left operand with the value specified after the operator.
((i+=1))
let "i+=1"
((i-=1))
let "i-=1"
  • In the following while loop, we are decrementing the value of the i variable by 5.
i=20

while [ $i -ge 5 ]
do
echo Number: $i
let "i-=5"
done
Number: 20
Number: 15
Number: 10
Number: 5

3. ++ and —

  • The ++ and — operators increment and decrement, respectively, its operand by 1 and return the value.
((i++))
((++i))
let "i++"
let "++i"
((i--))
((--i))
let "i--"
let "--i"
  • The operators can be used before or after the operand. They are also known as:
MEANING           | SYNTAX
------------------|-------
prefix increment | ++i
prefix decrement | --i
postfix increment | i++
postfix decrement | i--
  • Usually no difference; matters only if the result is bound elsewhere
x=5
y=$((x++))
echo x: $x
echo y: $y
x: 6
y: 5
x=5
y=$((++x))
echo x: $x
echo y: $y
x: 6
y: 6
  • Below is an example of how to use the postfix incrementor in a bash script:
#!/bin/bash
i=0
while true; do
if [[ "$i" -gt 3 ]]; then
exit 1
fi
echo i: $i
((i++))
done

4. links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com