第三章:Creating Utilities--24.一個交互式的計算器

   以前寫了第九個腳本,容許命令行調用bc進行浮點計算,因此如今必然要寫一個交互式的,基於命令行的計算器封裝腳本。它有一個優勢:即便加上幫助信息,也很短。 前端

#!/bin/sh
 
 # calc.sh -- 一個看起來像是bc的前端的命令行計算器
 
 scale=2
 
 show_help()
 {
     cat << EOF
 In addition to standard math function, calc also supports
 
    a % b    remainder of a/b
    a ^ b    exponential: a raised to the b power
    s(x)     sine of x, x in radians
    c(x)     cosine of x, x in radians
    a(x)     actangent of x, returns radians
    l(x)     natural log of x
    e(x)     exponential log of raising e to the x
    j(n, x)  bessel function of integer order n of x
    scale N  show N fractional digits(default = 2)
 
 EOF
 }
 
 if [ $# -gt 0 ]; then
     exec scriptbc.sh "$@"
 fi
 
 echo "Calc - a simple calculator. Enter 'help' for help, 'quit' to quit."
 
 echo -n "calc> "
 
 while read command args    # 像不像Python的順序解包
 do
     case $command in
         quit|exit) exit 0;;
         help|\?)   show_help;;
         scale)     scale=$args;;
         *)         scriptbc.sh -p $scale "$command" "$args";;
     esac
 
     echo -n "calc> "
 done
 
 echo ""
 
 exit 0

腳本如何運行:
可能這個腳本最有意思的部分就是那個while循環了。它建立一個calc>的提示,直到用戶完成輸入。固然,這個腳本的間接性成就了它本身:shell腳本並不須要特別的複雜。 git

運行腳本:
這個腳本跑起來很是簡單,由於它是一個交互式的,能夠提示用戶完成特定操做。若是有參數傳遞給它,它就轉而把這些參數傳給scripbc.sh。 shell

運行結果: ui

calc 150 / 3.5 
 42.85 
 
 ./calc.sh 
 Calc - a simple calculator. Enter 'help' for help, 'quit' to quit.
 calc> help
 In addition to standard math function, calc also supports
 
    a % b    remainder of a/b
    a ^ b    exponential: a raised to the b power
    s(x)     sine of x, x in radians
    c(x)     cosine of x, x in radians
    a(x)     actangent of x, returns radians
    l(x)     natural log of x
    e(x)     exponential log of raising e to the x
    j(n, x)  bessel function of integer order n of x
    scale N  show N fractional digits(default = 2)
 
 calc> 54354 ^ 3 
 160581137553864 
 
 calc> quit
相關文章
相關標籤/搜索