第三章:Creating Utilities--28.转换温度

   这个脚本中会出现不一样的数学公式。输入的气温能够是华氏、摄氏、开氏(绝对温度)。这个脚本时本书第一个应用复杂数学的地方,因此在这个脚本中你就能意识到以前写的第9个脚本是多有用了。由于这儿使用管道的思想与其相似。


代码: git

#!/bin/sh

# convertatemp.sh -- 气温转换脚本
# 容许用户输入华氏(F)、摄氏(C)、开氏(K)
# 输出会获得另2个计量单位中的等价气温

if [ $# -eq 0 ]; then
	cat << EOF >&2  # here document,同窗们,熟悉吗? 它是用于脚本中的交互式命令。
Usage: `basename $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

# sed -e 's/[-[[:digit:]]*//g'  原书中的unit,经测试,错误,本身修改了下
# sed -e 's/[^-[[:digit:]]*//g' 原书中的temp,同上
unit="$(echo $1 | sed -e 's/[[:digit:]]*//g' | tr '[:lower:]' '[:upper:]')"  # 获得$1中的字母
temp="$(echo $1 | sed -e 's/[^[:digit:]]*//g')"   # 获得$1中的数字

case ${unit:=F} in  # 设置变量默认值的方式
	F)  # 华氏转为摄氏的计算公式: Tc = (F - 32) / 1.8
	farm="$temp"
	cels="$(echo "scale=2;($farm-32)/1.8" | bc)"
	kelv="$(echo "scale=2;$cels+273.15" | bc)"
	;;
	C)  # 摄氏转华氏: Tf = (9 / 5) * Tc + 32
	cels=$temp
	kelv="$(echo "scale=2;$cels+273.15" | bc)"
	farm="$(echo "scale=2;((9/5)*$cels)+32" | bc)"
	;;
	K)  # 摄氏 = 开氏 - 273.15,而后使用摄氏转华氏公式
	kelv=$temp
	cels="$(echo "scale=2;$kelv-273.15" | bc)"
	farm="$(echo "scale=2;((9/5) * $cels)+32" | bc)"
esac

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

exit 0


运行脚本:
虽然在Unix命令行不多用到,但我(本书做者)仍是很喜欢这个脚本,由于它的输入有着直观的特性。输入是一个数值,它能够带有代表单位的后缀。
你之后会在第66个脚本中看到一样的单字母后缀,那个脚本时转换币值。

运行结果: shell

./convertatemp.sh 
Usage: convertatemp.sh 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

./convertatemp.sh 100c
Fahrenheit = 212.00
Celsius = 100
Kelvin = 373.15

./convertatemp.sh 100k
Fahrenheit = -279.67
Celsius = -173.15
Kelvin = 100

分析脚本:
也能够给脚本加上一个选项。而后能够这样运行:./converatemp.sh -c 100f 这样就能够获得摄氏中等价于华氏100度的气温了。

ps: 同窗们还记得第4个脚本--处理大数 中介绍的getopts的用法吗? 它能够处理-c这种参数。 测试

相关文章
相关标签/搜索