HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMinor

Fahrenheit / Celsius temperature converter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fahrenheitconvertertemperaturecelsius

Problem

This is a simple bash script (hopefully with a little style as well) for converting temperatures from Fahrenheit to Celsius and vice versa.

#!/bin/bash

re='^-*[0-9]+([.][0-9]+)?

Is there anything I could do to improve upon this? I am also curious if this would be portable / POSIX compliant. Everyone always says to use printf if portability is a concern. Is echo not portable? while true do printf "\n\e[1;39mWhat is the temperature you wish to convert?\e[0m\n\n\t" read -p "Enter a numeric value " n while [[ ! $n =~ $re ]] do printf '\t\e[3;3;31mInvalid selection\n\t\e[3;3;31m\e[0m\n\t' read -p "Enter a numeric value " n done echo printf "\n\tIs this \e[1;39m(F)\e[0mahrenheit or \e[1;39m(C)\e[0melsius\e[0m?\n\n" while true do read -sn 1 cf case $cf in [Ff] ) echo "$n""˚F = $(( ($n - 32) * 5 / 9 ))˚C"; break;; [cC] ) echo "$n""˚C = $(( $n * 9 / 5 + 32 ))˚F"; break;; * ) printf '\t\e[3;3;31mInvalid selection\n\e[3;3;31m\e[0m' printf '\tChoose \e[1;39m(F)\e[0mahrenheit or \e[1;39m(C)\e[0melsius\e[0m\n\n' esac done echo while true do printf "\tPress (1) to convert another\n\tpress (2) to quit" read -sn1 bye ; printf "\n\n" case $bye in [1] ) break ;; [2] ) printf "Now exiting" && exit ;; * ) printf '\t\e[3;3;31mInvalid selection\n\e[3;3;31m\e[0m' ;; esac done done


Is there anything I could do to improve upon this? I am also curious if this would be portable / POSIX compliant. Everyone always says to use printf if portability is a concern. Is echo not portable?

Solution

I don't know enough bash to offer you a technical review.

But, more philosophically: Have you considered writing this more in the style of a "program" than a "Press 1 to convert another"-type interface? Like:

~$ temperature c 30
86 ˚F
~$ temperature F 105
40 ˚C


My reasoning is that the above is easier and more flexible to use programatically, you don't need to write input loops at all and you can condense down to your core functionality:

#!/bin/bash

case $1 in
    [Ff] ) echo "$(( ($2 - 32) * 5 / 9 )) ˚C"; break;;
    [cC] ) echo "$(( $2 * 9 / 5 + 32 )) ˚F"; break;;
    *    ) echo "Usage: $0 c|f num"
esac

Code Snippets

~$ temperature c 30
86 ˚F
~$ temperature F 105
40 ˚C
#!/bin/bash

case $1 in
    [Ff] ) echo "$(( ($2 - 32) * 5 / 9 )) ˚C"; break;;
    [cC] ) echo "$(( $2 * 9 / 5 + 32 )) ˚F"; break;;
    *    ) echo "Usage: $0 c|f num"
esac

Context

StackExchange Code Review Q#140515, answer score: 9

Revisions (0)

No revisions yet.