Sitemap

Member-only story

Linux:Bash:PreVsPostIncrement

2 min readFeb 1, 2025

--

Here is a little note on the pre-increment versus the post-increment operator in Bash. I find it to be useful in both logic and math so I thought I’d make a short very short post.

A pre-increment, as the name implies, increments an integer variable by 1 before an operation while a post-increment increments the variable by 1 following the logical operation. For example,

$ # declare an integer variable and set it to 0
$ declare -i cnt=0
$ # pre-increment
$ (( ++cnt )) # pre increment the variable, should yield 1
$ echo "${cnt}"
1
$ (( cnt++ )) # post increment the variable, should yield 2
$ echo "${cnt}"
2
$ # The difference is apparent when used in a command
$ cnt=0
$ echo "$(( cnt++ ))" # operation before increment, should print 0
0
$ cnt=0; echo "$((++cnt))" # increment before operation, should print 1
1
$ ########
$ # Post increment when used as part of a logical condition
$ cnt=0
$ if (( cnt++ > 0 )); then # test logic then increment
> echo "true: cnt > 0 : ${cnt}"
> else
> #cnt was 0 when the conditional statement is tested
> #so this will print with cnt = 1
> echo "false : cnt = 0 : ${cnt}"
> fi
false : cnt = 0 : 1
$ ########
$ # Repeat with pre-increment
$ cnt=0
$ if (( ++cnt > 0 )); then # increment cnt then test the logic then
> #cnt was 1 when the conditional statement is tested
> #so this will print with cnt = 1
> echo "true: cnt > 0 : ${cnt}"
> else
> echo "false : cnt = 0 : ${cnt}"
> fi
true : cnt > 0 : 1

So that’s all I have to say about pre versus post incrementing in Bash!

--

--

Junky Birdbath
Junky Birdbath

Written by Junky Birdbath

This is my place to post notes on technical details. Pretty boring for most people. If interesting 4u, I'd like to interact.