第三章: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這種參數。 測試

相關文章
相關標籤/搜索