Bash · lesson 23 of 30 · Files and errors · bonusBuild a calculator
A pattern with =~ checks the line and BASH_REMATCH keeps its parts.
23-calculator.sh Download 23-calculator.sh
#!/usr/app/TurboShell/bin/bash
echo "Type a sum like 12 * 4. An empty line ends."
while read -rp "> " line && [[ -n $line ]]; do
if [[ ! $line =~ ^(-?(0|[1-9][0-9]*))\ *([-+*/])\ *(-?(0|[1-9][0-9]*))$ ]]; then
echo "Type whole number, sign, whole number"
continue
fi
a=${BASH_REMATCH[1]} sign=${BASH_REMATCH[3]} b=${BASH_REMATCH[4]}
case $sign in
+) echo $((a + b)) ;;
-) echo $((a - b)) ;;
'*') echo $((a * b)) ;;
/)
if ((b == 0)); then
echo "You cannot divide by zero"
else
awk -v a="$a" -v b="$b" 'BEGIN { printf "%.2f\n", a / b }'
fi
;;
esac
done
echo "Bye"
Terminal
$ bash 23-calculator.sh
Type a sum like 12 * 4. An empty line ends.
> 12 * 4
48
> 7 / 2
3.50
> 5 / 0
You cannot divide by zero
> 08 + 1
Type whole number, sign, whole number
>
ByeExercise
Add % for the remainder.