Increment and Decrement
Increment and decrement is like clicking a counter up or down by one each time someone walks in. You can also jump by bigger steps, such as adding five at once.
In this page:
Syntax
((variable++))
((variable--))
((variable += value))
Increment and Decrement
Bash supports ((x++)) and ((x--)) for increment/decrement, plus compound assignment like ((x += 5)). These only work inside arithmetic contexts like (( )), not as plain commands. They're the concise way to update a counter in a loop.
Note:
((x++)) returns the exit status based on the *original* value of x — if x was 0, the expression itself evaluates as "false" for set -e purposes.Example: Increment and Decrement
#!/bin/bash
count=0
((count++))
((count++))
((count += 5))
echo "Count: $count"
((count--))
echo "After decrement: $count"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
i++alone as a command, which is not valid; use((i++))ori=$((i+1)). - Not knowing that
((i++))returns exit status 1 when the value was 0, which fails underset -e. - Writing
i = i + 1with spaces, which is not an assignment.
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: