KandZ – Tuts

We like to help…!

Linux CLI 67 🐧 Number bases and conversion

a - Numbar bases in shell scripts
you can use variables with different bases by prefixing them with 0x for hexadecimal, 0 for octal, and 0b for binary.
*
num_hex=0x1A → hexadecimal
num_oct=025 → octal
num_bin=0b1010 → binary

when dealing with numbers in shell scripts, the shell might not handle leading zeros in variables.
025 it might be treated as decimal 25
so for example if you have a variable that's stored as octal, you have to make sure to use 0$var in the arithmetic expansion to interpret it as octal.
If you try to convert a string like 0x1G using $(( 0x$var )), bash will throw an error.
Hexadecimal is case-insensitive (1a == 1A), but other bases (octal, binary) use only digits.

b - base convertions in shell scripts
Converting from Another Base to Decimal
Octal to Decimal
Hexadecimal to Decimal
Binary to Decimal
Converting from Decimal to Another Base
Decimal to Octal
Decimal to Hexadecimal
Decimal to Binary

#linux #shell #cli #konsole #ubuntu #fedora

Leave a Reply