bash 计算器

输入两个数实现加减乘除运算

1,read

#!/bin/bash
print_usage () {                                    #定义一个函数,名字为print_usage
    printf "please enter an integer\n"             #打印符合脚本要求的提示信息
    exit 1 
}
read -p "please input first number: " firstnum

if [ -n "`echo $firstnum|sed 's/[0-9]//g'`" ]; then
#判断是否为整数,删除读入内容的数字部分看是否为空(-n功能),进而判断读入的内容是否为数字
    print_usage  #如果上诉条件变量不为空,说明不是整数,则调用用户帮助函数
fi
read -p "please input the operators: " operators
if [ "${operators}" != "+" ] && [ "${operators}" != "-" ] && [ "${operators}" != "*" ] && [ "${operators}" != "/" ]; then
    echo "please use{+|-|*|/}"
    exit 2
fi
read -p  "please input second number: " secondnum
if [ -n "`echo $secondnum|sed 's/[0-9]//g'`" ]; then
    print_usage
fi
echo "${firstnum}${operators}${secondnum}=$((${firstnum}${operators}${secondnum}))"

2. printf

#!/bin/bash
print_usage () {
    printf $"USAGE:$0 NUM1 {+|-|*|/} NUM2\n"
    exit 1
  }

    if [ $# -ne 3 ] #如果脚本传入的参数不等于3个(两个数字一个运算符号)
        then
            print_usage
    fi

firstnum=$1
secondnum=$3
op=$2

    if [ -n "`echo $firstnum|sed 's/[0-9]//g'`"]
        then
	    print_usage
    fi

    if [ "$op" != "+" ]&&[ "$op" != "-" ]&&[ "$op" != "*" ]&&[ "$op" != "/" ]
        then
            print_usage
    fi

    if [ -n "`echo $secondnum|sed 's/[0-9]//g'`"]
        then
            print_usage
    fi
    echo "${firstnum}${op}${secondnum}=$((${firstnum}${op}${secondnum}))"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值