Home > Net >  convert temp from Celsius to Fahrenheit?
convert temp from Celsius to Fahrenheit?

Time:06-01

#!/bin/bash
read -p "Enter degree celsius temperature: " C
F=$(1.8*{$C}) 32
echo The temperature in Fahrenheit is $F

in above shell script i am trying to convert temp from Celsius to Fahrenheit

getting this error

/code/source.sh: line 3: 1.8{32}: command not found The temperature in Fahrenheit is 32*

Ans should be 89

CodePudding user response:

You can also use awk for the floating point calculation and you can control the output format with printf:

#!/bin/bash
read -p "Enter degree celsius temperature: " c
awk -v c="$c" 'BEGIN {printf("The temperature in Fahrenheit is %.2f\n", 1.8 * c   32)}'

CodePudding user response:

#!/bin/bash
read -p "Enter degree celsius temperature: " C
F=`echo "1.8 * $C   32" | bc`
echo The temperature in Fahrenheit is $F

CodePudding user response:

For 32 (°C) your formula 1.8*32 32 should yield 89.6 (°F) but as you mention Ans should be 89 so we'll forget about the decimals and use $((180*$f/100 32)) instead so your program becomes (untested):

#!/bin/bash
read -p "Enter degree celsius temperature: " c
f=$((180*$c/100 32))
echo The temperature in Fahrenheit is $f

Output:

89

Basically Bash won't allow you to use decimals (1.8) but you can replace it with a fraction (180/100). Bash can compute with it but you'll lose the decimals (89.6 -> 89).

CodePudding user response:

With bash only, and with a 0.1 accuracy:

$ cat c2f
#!/usr/bin/env bash

declare -i C F
read -p "Enter degree celsius temperature: " C
F=$(( 18 * C   320 ))
echo "The temperature in Fahrenheit is ${F:0: -1}.${F: -1: 1}"

$ ./c2f
Enter degree celsius temperature: 32
The temperature in Fahrenheit is 89.6

If you are not interested in the fractional part but want a rounding to the nearest integer:

$ cat c2f
#!/usr/bin/env bash

declare -i C F
read -p "Enter degree celsius temperature: " C
F=$(( 18 * C   325 ))
echo "The temperature in Fahrenheit is ${F:0: -1}"

$ ./c2f
Enter degree celsius temperature: 32
The temperature in Fahrenheit is 90
  • Related