本站内容有下面分类知识,欢迎您的到来^_^

shell相关:指令篇 基础篇 脚本欣赏 编程实例 shell问问 shell视频教程 技巧篇 水平测试 E文资料 vi编辑器 高级Bash脚本编程指南
其他:mysql perl c语言

设soyo123为首页 收藏本站
当前位置:|主页>shell相关E文资料>

#28 Converting Temperatures

百度收藏 QQ搜藏

This script works with a variety of mathematical formulas, and an unusual input format, to translate between Fahrenheit, Celsius, and Kelvin. It's the first use of sophisticated mathematics within a script in this book.

The Code
#!/bin/sh

# convertatemp - Temperature conversion script that lets the user enter
#   a temperature in Fahrenheit, Celsius, or Kelvin and receive the
#   equivalent temperature in the other two units as the output.

if [ $# -eq 0 ] ; then
  cat << EOF >&2
Usage: $0 temperature[F|C|K]
where the suffix:
   F    indicates input is in Fahrenheit (default)
   C    indicates input is in Celsius
   K    indicates input is in Kelvin
EOF
  exit 1
fi

unit="$(echo $1|sed -e 's/[-[[:digit:]]*//g' | tr '[:lower:]' '[:upper:]' )"
temp="$(echo $1|sed -e 's/[^-[[:digit:]]*//g')"

case ${unit:=F}
in
   F ) # Fahrenheit to Celsius formula: Tc = (F - 32) / 1.8
   farn="$temp"
   cels="$(echo "scale=2;($farn - 32) / 1.8" | bc)"
   kelv="$(echo "scale=2;$cels + 273.15" | bc)"
   ;;

   C ) # Celsius to Fahrenheit formula: Tf = (9/5)*Tc+32
   cels=$temp
   kelv="$(echo "scale=2;$cels + 273.15" | bc)"
   farn="$(echo "scale=2;((9/5) * $cels) + 32" | bc)"
   ;;

   K ) # Celsius = Kelvin - 273.15, then use Cels -> Fahr formula
   kelv=$temp
   cels="$(echo "scale=2; $kelv - 273.15" | bc)"
   farn="$(echo "scale=2; ((9/5) * $cels) + 32" | bc)"
esac

echo "Fahrenheit = $farn"
echo "Celsius    = $cels"
echo "Kelvin     = $kelv"

exit 0

Running the Script
I really like this script because I like the intuitive nature of the input format, even if it is pretty unusual for a Unix command. Input is entered as a numeric value, with an optional suffix that indicates the units of the temperature entered. To see the Celsius and Kelvin equivalents of the temperature 100 degrees Fahrenheit, enter 100F. To see what 100 degrees Kelvin is equivalent to in Fahrenheit and Celsius, use 100K. If no unit suffix is entered, this script works with Fahrenheit temperatures by default.


The Results
$ convertatemp 212
Fahrenheit = 212
Celsius    = 100.00
Kelvin     = 373.15
$ convertatemp 100C
Fahrenheit = 212.00
Celsius    = 100
Kelvin     = 373.15
$ convertatemp 100K
Fahrenheit = -279.67
Celsius    = -173.15
Kelvin     = 100

Hacking the Script
A few input flags that would generate a succinct output format suitable for use in other scripts would be a useful addition to this script. Something like convertatemp -c 100f could output the Celsius equivalent of 100 degrees Fahrenheit.


上一篇:#27 Adding a Local Dictionary to Spell 下一篇:#29 Calculating Loan Payments
power by soyo123 2007-2008