创建计算器脚本

J H*_*ard 3 unix bash shell

我正在尝试使用bash脚本制作计算器.用户输入一个数字,选择是否要加,减,乘或除.然后用户输入第二个数字,并且能够选择是否进行求和,或者在循环上再次进行加,减,乘或除.

我现在无法解决这个问题

echo Please enter a number
read number

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide
read operation

case $operation in
    1) math='+';;
    2) math='-';;
    3) math='*';;
    4) math='/';;
    *) math='not an option, please select again';;
esac
echo "$number $math"


echo Please enter a number
read number2

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide, 5: Equals
read operation2
case $operation2 in
    1)math2='Add';;
    2)math2='Subtract';;
    3)math2='Multiply';;
    4)math2='Divide';;
    5)math2='Equals';;
    *)math2='not an option, please select again';;
esac
echo You have selected $math2

exit 0
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所做的,但任何人都可以帮我解决如何循环计算器的问题吗?

小智 5

这个怎么样

calc ()
{
  (( d = $1 ))
  echo $d
}
Run Code Online (Sandbox Code Playgroud)

产量

$ calc '6 + 2'
8

$ calc '6 - 2'
4

$ calc '6 * 2'
12

$ calc '6 / 2'
3
Run Code Online (Sandbox Code Playgroud)


gle*_*man 5

鲜为人知的 shell 内置命令select对于这种菜单驱动的程序非常方便:

#!/bin/bash
while true; do
    read -p "what's the first number? " n1
    read -p "what's the second number? " n2
    PS3="what's the operation? "
    select ans in add subtract multiply divide; do
        case $ans in 
            add) op='+' ; break ;;
            subtract) op='-' ; break ;;
            multiply) op='*' ; break ;;
            divide) op='/' ; break ;;
            *) echo "invalid response" ;;
        esac
    done
    ans=$(echo "$n1 $op $n2" | bc -l)
    printf "%s %s %s = %s\n\n" "$n1" "$op" "$n2" "$ans"
done
Run Code Online (Sandbox Code Playgroud)

样本输出

what's the first number? 5
what's the second number? 4
1) add
2) subtract
3) multiply
4) divide
what's the operation? /
invalid response
what's the operation? 4
5 / 4 = 1.25000000000000000000
Run Code Online (Sandbox Code Playgroud)

如果我想使用 bash v4 功能和 DRY:

#!/bin/bash

PS3="what's the operation? "
declare -A op=([add]='+' [subtract]='-' [multiply]='*' [divide]='/')

while true; do
    read -p "what's the first number? " n1
    read -p "what's the second number? " n2
    select ans in "${!op[@]}"; do
        for key in "${!op[@]}"; do
            [[ $REPLY == $key ]] && ans=$REPLY
            [[ $ans == $key ]] && break 2
        done
        echo "invalid response"
    done
    formula="$n1 ${op[$ans]} $n2"
    printf "%s = %s\n\n" "$formula" "$(bc -l <<< "$formula")"
done
Run Code Online (Sandbox Code Playgroud)