代码: 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
运行结果: 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这种参数。 测试