2026-01-21 18:06:34 +08:00

32 lines
773 B
Bash
Executable File

#!/usr/bin/env bash
read -r INPUT
echo "$INPUT"
error() {
echo "{\"error\":\"$1\"}"
exit 0
}
A=$(echo "$INPUT" | jq -r '.a // empty')
OP=$(echo "$INPUT" | jq -r '.op // empty')
B=$(echo "$INPUT" | jq -r '.b // empty')
[[ -z "$A" || -z "$OP" || -z "$B" ]] && error "missing parameter"
is_number='^-?[0-9]+([.][0-9]+)?$'
[[ ! "$A" =~ $is_number ]] && error "a is not a number"
[[ ! "$B" =~ $is_number ]] && error "b is not a number"
case "$OP" in
"+") RESULT=$(echo "$A + $B" | bc) ;;
"-") RESULT=$(echo "$A - $B" | bc) ;;
"*") RESULT=$(echo "$A * $B" | bc) ;;
"/")
[[ "$(echo "$B == 0" | bc)" -eq 1 ]] && error "division by zero"
RESULT=$(echo "scale=10; $A / $B" | bc)
;;
*) error "unsupported operator" ;;
esac
echo "{\"result\": $RESULT}"