使用Shell编写简单的计算器

2014-12-01 14:57
function j2calc () 
{ 
    local Result;
    if [ $# -lt 1 ]; then
        echo "没有输入正确表达式";
    elif (( $* )); then
        let Result="$*";
        echo "$* = $Result";
    else
        echo "结果为0或非法表达式";
    fi
}

运算结果(BASH只能保留整数,没有小数)

root / # j2calc "3 + (4**3 / 2)"
3 + (4**3 / 2) = 35
root / # j2calc "2 * 3 + 5 / 4"
2 * 3 + 5 / 4 = 7
root / # j2calc 0xFF
0xFF = 255
root / # j2calc 015
015 = 13

参考:http://www.ibm.com/developerworks/cn/linux/l-bash-test.html


原文链接: http://blog.jtwo.me/use-shell-to-write-calculator