Creating a calculator script

后端 未结 7 2143
悲哀的现实
悲哀的现实 2020-12-17 06:18

I am trying to make a calculator with a bash script. The user enters a number, chooses whether they wish to add, subtract, multiply or divide. Then the user enters a second

7条回答
  •  长情又很酷
    2020-12-17 06:29

    The lesser-known shell builtin command select is handy for this kind of menu-driven program:

    #!/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
    

    Sample output

    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
    

    If I was going to get fancy with bash v4 features and 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
    

提交回复
热议问题