0
0
Bash-scriptingConversionBeginner · 2 min read

Bash Script to Convert Octal to Decimal Number

Use Bash's built-in arithmetic expansion with $((8#octal_number)) to convert an octal number to decimal, for example: decimal=$((8#123)).
📋

Examples

Input10
Output8
Input123
Output83
Input0
Output0
🧠

How to Think About It

To convert octal to decimal in Bash, treat the input as a base-8 number and use Bash's arithmetic expansion with the base prefix 8#. This tells Bash to interpret the number as octal and convert it to decimal automatically.
📐

Algorithm

1
Get the octal number input as a string.
2
Use Bash arithmetic expansion with <code>8#</code> prefix to interpret the input as octal.
3
Store the result as a decimal number.
4
Print the decimal number.
💻

Code

bash
#!/bin/bash
read -p "Enter an octal number: " octal
# Convert octal to decimal using base 8 prefix
decimal=$((8#$octal))
echo "Decimal value: $decimal"
Output
Enter an octal number: 123 Decimal value: 83
🔍

Dry Run

Let's trace the input '123' through the code

1

Read input

octal='123'

2

Convert using arithmetic expansion

decimal=$((8#123)) which equals 83

3

Print result

Output: 'Decimal value: 83'

Octal InputDecimal Output
12383
💡

Why This Works

Step 1: Using base prefix

The 8# prefix tells Bash to treat the following number as base 8 (octal).

Step 2: Arithmetic expansion

Bash evaluates $((8#number)) and converts it to decimal automatically.

Step 3: Output the decimal

The converted decimal value is stored and printed to the user.

🔄

Alternative Approaches

Using printf
bash
read -p "Enter octal: " octal
decimal=$(printf "%d" "$octal")
echo "Decimal: $decimal"
Uses printf to convert octal string to decimal; simpler but less flexible for invalid input.
Using bc calculator
bash
read -p "Enter octal: " octal
decimal=$(echo "ibase=8; $octal" | bc)
echo "Decimal: $decimal"
Uses bc for conversion; useful if you want to handle very large numbers or more complex math.

Complexity: O(1) time, O(1) space

Time Complexity

Conversion is done in constant time since Bash arithmetic expansion handles it internally without loops.

Space Complexity

Only a few variables are used to store input and output, so space is constant.

Which Approach is Fastest?

Using Bash arithmetic expansion is fastest and simplest; printf and bc add overhead but offer alternatives.

ApproachTimeSpaceBest For
Bash arithmetic expansionO(1)O(1)Simple, fast conversion
printfO(1)O(1)Quick conversion with built-in tool
bc calculatorO(1)O(1)Handling large numbers or complex math
💡
Use $((8#octal_number)) in Bash for quick and reliable octal to decimal conversion.
⚠️
Forgetting to prefix the number with 8# causes Bash to treat it as decimal, giving wrong results.