Bash has an interesting builtin feature to convert from any base to decimal, which is a part of bash’s arithmetic evaluation features. In this post i will quickly introduce you with this feature.
Arithmetic Expansion
To allow arithmetic evaluation of an expression and substitution of the result bash has the following construct.
$((expression))
For example
echo $((2 + 5))
The above will evaluate the expression 2 + 5 substitute with the result, which will be displayed by echo.
Any to decimal conversion
Now to come to the point. Consider the following construct.
echo $((2#1010))
This will print out 10 , that is the decimal equivalent of the binary (base 2) 1010 . The general construct is:
echo $((base#number))
Where the base is the value of the base in which the number is in. The value of base can be from 2 upto 64. After 10 base first lower case characters are used to represent additional base digits, when the base value is greater than 32 upper case characters are used. In the case of base value 63 and 64, the 63rd and 64th digit of the base are the @ and _ symbols respectively.
Also to represent hexadecimal you can start the hex number by 0x or 0X, and to denote an octal number you can start the number with 0 as normal. Like
echo $((0xa)) echo $((012))
Both of these will print out 10, which is the decimal equivalent of 0xa in hex and 012 in octal.
The same can be achieved by
echo $((16#a)) echo $((8#12))
At last for completeness i should also add that without any of the 0x, or 0 appended or the base#number format, plain integers are considered to be in decimal, ie. in base 10 by default.
Although you can only convert any integer base (within 2 and 64, both inclusive) to decimal, and not other base, this can come in handy.
References
- man bash ARITHMETIC EVALUATION section






