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:
i=$((i+1))
((i=i+1))
let "i=i+1"
i=$((i-1))
((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:
i=0
until [ $i -gt 3 ]
do
echo i: $i
((i=i+1))
done
The += and -= Operators
Bash also provides assignment operators, +=
and -=
:
((i+=1))
let "i+=1"
((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:
i=20
while [ $i -ge 5 ]
do
echo Number: $i
let "i-=5"
done
Using ++ and — Operators
The ++
and --
operators increment and decrement the operand by 1:
((i++))
((++i))
let "i++"
let "++i"
((i--))
((--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:
x=5
y=$((x++))
echo x: $x
echo y: $y
And an example of postfix increment in a script:
#!/bin/bash
i=0
while true; do
if [[ "$i" -gt 3 ]]; then
exit 1
fi
echo i: $i
((i++))
done
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.