why bash increment: `n=0;((n++));` return error?

n=0;
((n++));echo "ret=$?;n=$n;"
((n++));echo "ret=$?;n=$n;"
((n++));echo "ret=$?;n=$n;"

from n=1 on, ((n++)) works correctly,
only when n=0, ((n++)) return error,
and I am using a trap '' ERR that is causing trouble with that

is it some bug?

Asked By: Aquarius Power

||

It’s because the return value of (( expression )) is not used for error indication. From the bash manpage:

((expression))

The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to letexpression“.

So, in your case, because the value of the expression is zero, the return status of (( ... )) is 1.

Answered By: smheidrich

The reason is as pmos writes above.

One solution would be to use ((++n)) to do increment. Your expression will never evaluate to zero, and so never look like it causes an error.

Answered By: user732

You should do:

echo "$((n+=1))"

It will not raise any traps – its only return comes from echo.

Or if you desire to use it as a standalone, in cases in which $n remains less than some 20 digits the following two forms always return true:

n=$((n+1))

Or :

: "$((n+=1))"
Answered By: mikeserv
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.