bash 计算器
输入两个数实现加减乘除运算
1,read
#!/bin/bash
print_usage () { #定义一个函数,名字为print_usageprintf "please enter an integer\n" #打印符合脚本要求的提示信息exit 1
}
read -p "please input first number: " firstnumif [ -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}" != "/" ]; thenecho "please use{+|-|*|/}"exit 2
fi
read -p "please input second number: " secondnum
if [ -n "`echo $secondnum|sed 's/[0-9]//g'`" ]; thenprint_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个(两个数字一个运算符号)thenprint_usagefifirstnum=$1
secondnum=$3
op=$2if [ -n "`echo $firstnum|sed 's/[0-9]//g'`"]thenprint_usagefiif [ "$op" != "+" ]&&[ "$op" != "-" ]&&[ "$op" != "*" ]&&[ "$op" != "/" ]thenprint_usagefiif [ -n "`echo $secondnum|sed 's/[0-9]//g'`"]thenprint_usagefiecho "${firstnum}${op}${secondnum}=$((${firstnum}${op}${secondnum}))"
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
