Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Arithmetic $number != $((number))

Tags:

bash

When trying to execute a simple bash script to increment a number with preceding 0's by 1, the original number is interpreted incorrectly.

#!/bin/bash
number=0026
echo $number
echo $((number))
echo $((number+1))

When this command is executed I get the output:

0026
22
23

Why does this occur?

like image 836
Oliver Hemsted Avatar asked Aug 13 '15 14:08

Oliver Hemsted


1 Answers

To force base-10 representation:

$ echo $((10#$number))
26
$ echo $((10#$number + 1))
27

Responding to kojiro's comment:

$ something=08
$ echo $((something))
bash: 08: value too great for base (error token is "08")
$ echo $(($something))
bash: 08: value too great for base (error token is "08")
$ echo $((10#something))
bash: 10#something: value too great for base (error token is "10#something")
$ echo $((10#$something))
8
$ echo $((08))
bash: 08: value too great for base (error token is "08")
$ echo $((10#08))
8

$ echo $(( 16#10 ))
16
$ echo $(( 16#f ))
15
$ echo $(( 16#10 - 1 ))
15
like image 123
glenn jackman Avatar answered Oct 14 '22 10:10

glenn jackman