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

Cyrus
  • 84,225
  • 14
  • 89
  • 153

4 Answers4

2

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)}'

or we can remove the bash parts and have an awk only solution

#!/usr/bin/awk -f
BEGIN {
    printf("Enter degree celsius temperature "); getline c;
    printf("The temperature in Fahrenheit is %.2f\n", 1.8 * c + 32)
}
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0
#!/bin/bash
read -p "Enter degree celsius temperature: " C
F=`echo "1.8 * $C + 32" | bc`
echo The temperature in Fahrenheit is $F
gameiplay0
  • 71
  • 4
0

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*$c/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 or 18/10 or even 9/5, see the comments). Bash can compute with it but you'll lose the decimals (89.6 -> 89).

James Brown
  • 36,089
  • 7
  • 43
  • 59
  • I'm curious why you went with `180/100` instead of `18/10` – glenn jackman Jun 01 '22 at 12:52
  • 1
    0°C = 32°F and 100°C = 212°F. 212-32=180 and 100-0=100. I've got some background in physics, really didn't even think about it. I've used to: _C_ × 2 -10% + 32 = _F_ in head, tho. 9/5 would've been even shorter. – James Brown Jun 01 '22 at 13:53
0

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
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51