J Homard - 1 year ago 54

Bash Question

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 number and is able to choose whether to do the sum, or add, subtract, multiply or divide again on a loop.

I cannot rack my head around this right now

`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

This is what I have done so far, but can anyone help me work out how to loop back on the calculator?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**