#! /bin/bash checkInt() { arr=$1 for i in "${arr[@]}" ; do temp=`echo $i | sed 's/[0-9]//g' | sed 's/[ ]*//g'` if [ -n "$temp" ]; then echo "$i must be integer" return 1 fi done return 0 } fuhao="" #判断符号 getFuhao() { f=$(echo $1 | grep +) if [ -n "$f" ]; then fuhao="+" fi f=$(echo $1 | grep -) if [ -n "$f" ]; then fuhao="-" fi f=$(echo $1 | grep x) if [ -n "$f" ]; then fuhao="x" fi f=$(echo $1 | grep /) if [ -n "$f" ]; then fuhao="/" fi #echo "fuhao=$fuhao" } getLast() { arr=$1 last=0; case $fuhao in "+") last=$((${arr[0]} + ${arr[1]})) ;; "-") last=$((${arr[0]} - ${arr[1]})) ;; "x") last=$((${arr[0]} * ${arr[1]})) ;; "/") last=$((${arr[0]} / ${arr[1]})) ;; esac echo "${arr[0]} $fuhao ${arr[1]} = $last" } r="" #输入 checkinputAndCompute() { while true; do echo "please input two num to plus, eg: a +-x/ b" read r if [ -z "$r" ]; then echo "cannot be null" else r=`echo "$r" | sed 's/\\*/x/'` getFuhao $r arr=(${r//$fuhao/ }) if [ ${#arr[@]} -ne 2 ]; then echo "error input, eg: a +-x/ b" else if checkInt $arr; then getLast $arr fi fi fi done } checkinputAndCompute
#! /bin/bash标签:arr,shell,last,fuhao,grep,整数,echo,计算器,fi From: https://www.cnblogs.com/trump2/p/17723060.html
checkInt() {
arr=$1
for i in "${arr[@]}" ; do
temp=`echo $i | sed 's/[0-9]//g' | sed 's/[ ]*//g'`
if [ -n "$temp" ]; then
echo "$i must be integer"
return 1
fi
done
return 0
}
fuhao="" #判断符号
getFuhao() {
f=$(echo $1 | grep +)
if [ -n "$f" ]; then
fuhao="+"
fi
f=$(echo $1 | grep -)
if [ -n "$f" ]; then
fuhao="-"
fi
f=$(echo $1 | grep x)
if [ -n "$f" ]; then
fuhao="x"
fi
f=$(echo $1 | grep /)
if [ -n "$f" ]; then
fuhao="/"
fi
#echo "fuhao=$fuhao"
}
getLast() {
arr=$1
last=0;
case $fuhao in
"+")
last=$((${arr[0]} + ${arr[1]}))
;;
"-")
last=$((${arr[0]} - ${arr[1]}))
;;
"x")
last=$((${arr[0]} * ${arr[1]}))
;;
"/")
last=$((${arr[0]} / ${arr[1]}))
;;
esac
echo "${arr[0]} $fuhao ${arr[1]} = $last"
}
r="" #输入
checkinputAndCompute() {
while true; do
echo "please input two num to plus, eg: a +-x/ b"
read r
if [ -z "$r" ]; then
echo "cannot be null"
else
r=`echo "$r" | sed 's/\\*/x/'`
getFuhao $r
arr=(${r//$fuhao/ })
if [ ${#arr[@]} -ne 2 ]; then
echo "error input, eg: a +-x/ b"
else
if checkInt $arr; then
getLast $arr
fi
fi
fi
done
}
checkinputAndCompute