bash - 创建计算器脚本

标签 bash shell unix

我正在尝试用 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

这是我到目前为止所做的,但是谁能帮我弄清楚如何在计算器上循环返回?

最佳答案

鲜为人知的 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

示例输出

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

如果我想看中 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

关于bash - 创建计算器脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350556/

相关文章:

bash - Chef - 在 Ubuntu 中使用本地存储库

Python DNS服务器IP地址查询

linux - 我应该对同一文件上的并行 sed 执行进行竞争条件检查吗?

linux - 当新文件到达供应商时,bash 文件 cron 作业出现问题

java - 通过java运行ab-initio图?

php - 创建在 Unix 上运行发布脚本的 PHP 页面

bash - AWK 寻找一种方法来打印包含逗号分隔字符串中的单词的行

bash - 使用JSON中的jq获取键值

json - 将多个文件与分隔符合并为一个文件

rest - 通过远程访问 API 访问 Docker for Mac