代碼: 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這種參數。 測試