Bash Script to Convert Celsius to Fahrenheit
F = (C * 9/5) + 32 in a Bash script like fahrenheit=$(echo "scale=2; ($celsius * 9/5) + 32" | bc) to convert Celsius to Fahrenheit.Examples
How to Think About It
bc to perform the calculation and keep decimal precision.Algorithm
Code
#!/bin/bash read -p "Enter temperature in Celsius: " celsius fahrenheit=$(echo "scale=2; ($celsius * 9/5) + 32" | bc) echo "$celsius Celsius is $fahrenheit Fahrenheit"
Dry Run
Let's trace converting 25 Celsius to Fahrenheit through the code
Input Celsius
User enters 25
Calculate Fahrenheit
Calculate (25 * 9/5) + 32 = 45 + 32 = 77.00 using bc
Print Result
Output: '25 Celsius is 77.00 Fahrenheit'
| Step | Celsius | Calculation | Fahrenheit |
|---|---|---|---|
| 1 | 25 | 25 * 9/5 + 32 | 77.00 |
Why This Works
Step 1: Formula for Conversion
The formula F = (C * 9/5) + 32 converts Celsius to Fahrenheit by scaling and shifting the temperature.
Step 2: Using bc for Decimal Math
Bash cannot do floating-point math directly, so bc is used to calculate with decimals and precision.
Step 3: Reading Input and Output
The script reads Celsius from the user, calculates Fahrenheit, then prints the result clearly.
Alternative Approaches
#!/bin/bash read -p "Enter Celsius: " celsius fahrenheit=$(awk "BEGIN {print ($celsius * 9/5) + 32}") echo "$celsius Celsius is $fahrenheit Fahrenheit"
#!/bin/bash read -p "Enter Celsius: " celsius fahrenheit=$(( (celsius * 9 / 5) + 32 )) echo "$celsius Celsius is $fahrenheit Fahrenheit"
Complexity: O(1) time, O(1) space
Time Complexity
The script performs a fixed number of arithmetic operations and input/output steps, so it runs in constant time.
Space Complexity
It uses a few variables and no extra data structures, so space usage is constant.
Which Approach is Fastest?
Integer math is fastest but less precise; using bc or awk adds slight overhead but supports decimals accurately.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using bc | O(1) | O(1) | Accurate decimal math |
| Using awk | O(1) | O(1) | Simpler decimal math without bc |
| Integer math | O(1) | O(1) | Fast, approximate results |
bc or awk in Bash to handle decimal calculations like temperature conversion.bc or awk causes errors or wrong results.