Bash Script to Convert Decimal to Octal Number
Use the Bash command
printf '%o' decimal_number to convert a decimal number to octal; for example, printf '%o\n' 10 outputs 12.Examples
Input10
Output12
Input64
Output100
Input0
Output0
How to Think About It
To convert decimal to octal, think of representing the decimal number in base 8 instead of base 10. Bash's
printf command can format numbers in octal using the %o specifier, which directly converts and prints the number in octal form.Algorithm
1
Get the decimal number input from the user or argument2
Use the printf command with the '%o' format specifier to convert the decimal number to octal3
Print the converted octal numberCode
bash
#!/bin/bash # Read decimal number from user read -p "Enter a decimal number: " decimal # Convert decimal to octal and print printf '%o\n' "$decimal"
Output
Enter a decimal number: 10
12
Dry Run
Let's trace the input 10 through the script
1
Input decimal number
User enters 10, so variable decimal=10
2
Convert decimal to octal
printf '%o\n' 10 converts decimal 10 to octal 12
3
Print result
Output printed is '12'
| decimal | printf '%o' output |
|---|---|
| 10 | 12 |
Why This Works
Step 1: Reading input
The script reads the decimal number as a string and stores it in a variable.
Step 2: Using printf for conversion
The printf '%o' command formats the decimal number into octal representation.
Step 3: Outputting the octal number
The script prints the octal number with a newline for clear output.
Alternative Approaches
Using bc command
bash
#!/bin/bash read -p "Enter decimal number: " dec echo "obase=8; $dec" | bc
This uses the bc calculator to convert decimal to octal; it is flexible but requires bc installed.
Using shell arithmetic expansion
bash
#!/bin/bash read -p "Enter decimal number: " dec octal=$((10#$dec)) echo "$(printf '%o' "$octal")"
This ensures the input is treated as decimal before converting to octal with printf.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion using printf or bc is constant time since it processes a single number without loops.
Space Complexity
Only a few variables are used, so space usage is constant.
Which Approach is Fastest?
Using printf is fastest and simplest; bc is more flexible but slower due to spawning a process.
| Approach | Time | Space | Best For |
|---|---|---|---|
| printf '%o' | O(1) | O(1) | Simple, fast conversion |
| bc command | O(1) | O(1) | Flexible base conversions |
| Arithmetic expansion + printf | O(1) | O(1) | Safe input handling |
Use
printf '%o' for quick and reliable decimal to octal conversion in Bash.Forgetting to quote the variable in
printf can cause errors if input is empty or invalid.