When writing Bash scripts you will often need to increment or decrement a variable. There are multiple ways in which you can do this. This guide will show you two popular methods of doing exactly that!
This tutorial describes how to compare strings in Bash.
Related: How to concatenate strings in Bash
Method 1: Incrementing or decrementing a variable using arithmetic expansion
Arithmetic expansion is a concept in bash where you can evaluate an expression and substitute the result of that expression in one single command.
Using Bash's Arithmetic Expansion feature is the suggested method for evaluating arithmetic expressions using integers. Thanks to this built-in shell extension, you can do mathematical operations using parentheses ((...)).
The Bash arithmetic expansion has the format
$((arithmetic expression)). The outcome of the most recent expression supplied will be returned by the shell expansion.
The ((...)) notation is referred to as a compound command used to evaluate an arithmetic expression in Bash, whereas the $((...)) notation is what is known as the Arithmetic Expansion.
Here's how you can use expansion to increment a variable.
$ a=3 && echo $a 3 $ echo $((a+2)) 5 $ a=$((a+3)) $ echo $a 6
Within Arithmetic expansion, you can also use the
-- arithmetic operators to increment or decrement a variable. For example:
$ var=6 && echo $var 6 $ echo $((var++)) 6 $ echo $var 7 $ echo $((++var)) 8 $ echo $var 8
Method 2: Using
let to perform arithmetic operations
For evaluating mathematical expressions, Linux systems come with a built-in concept called bash
let. Let is a straightforward command with its own environment, unlike other arithmetic evaluation and expansion instructions. Arithmetic expansion is also possible with the
After establishing variable values, you may execute simple math operations by using the
let command. For instance, do addition, subtraction, multiplication, division, and modulus.
Here's an example of using
let to increment or decrement a variable.
$ let "a = 6" "b = 2" "c=a+b"; echo $c 8 $ let "a = 6" "b = 2" "c=a-b"; echo $c 4 let "a = 6" "b = 2" "a=a+b"; echo $a 8
Incrementing or decrementing variables is one of the most important things you will need to know how to do when writing bash scripts - we hope this article helps you do exactly that!