以前写了第九个脚本,容许命令行调用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