Search code examples
bashshellfloating-pointarithmetic-expressions

convert temp from Celsius to Fahrenheit?


#!/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


Solution

  • 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