Issue
Given a math operation in bash like
a=$(( ${b} + 1 ))
how do I handle cases where b
can be either positive or negative with leading zeros? If I try
a=$(( 10#${b} + 1 ))
for b=009
, this is successful. But if I try the same for b=-001
, this returns an error:
10#: invalid integer constant (error token is "10#")
So is there a way to handle these sorts of cases in a single line? Or is there a way to check if b
is less than 0? For the latter option, I have tried
[[ $b < 0 ]] && a=$(( ${b} + 1 )) || a=$(( 10#${b} + 1 ))
but this runs into a similar error in the conditional if b
is greater than or equal to 008
.
PS: the reason I need the 10#
prefix is that numbers starting with leading zeros are interpreted as octal otherwise.
Solution
The syntax to specify the base expects the negative sign, if any, before the base specifier.
$ echo $(( -10#0123 + 1 ))
-122
So something like this could work:
b=-009
b_with_base="10#$b"
echo $(( ${b_with_base/10#-/-10#} + 1 ))
outputs -8
with b=-009
and 10
with b=009
.
Answered By - joanis Answer Checked By - Timothy Miller (WPSolving Admin)