代码:
#!/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个脚本中看到同样的单字母后缀,那个脚本时转换币值。
运行结果:
./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这种参数。