Build an Interactive Calculator
This project builds calc.sh, a command-line calculator with a prompt, line editing and history, decimal numbers, variables, a few functions and clear error messages. It works in three modes: interactively at a calc> prompt, as a one-shot command (calc.sh '2 * (3 + 4)'), and as a filter that evaluates one line after another from a pipe or a file.
A calculator sounds like a small task, but it touches a surprising number of topics from this tutorial: reading input with read, parsing text with [[ =~ ]] and BASH_REMATCH, associative arrays, functions with return codes, parameter expansion, case dispatching, detecting a terminal, and, most importantly, handling untrusted input safely.
What the Calculator Should Do
Before writing code, it helps to list the requirements:
- Decimal arithmetic.
10 / 4must give2.5, not2. - Operators and parentheses:
+ - * / ^with the usual precedence, and( )for grouping. - Functions and constants:
sqrt(x),mod(a, b)for the remainder, andpi. - Variables:
rate = 0.18stores a value;ansalways holds the last result. - Commands:
help,vars,scale N(number of decimal places),clear,quit. - Helpful errors for division by zero, unknown names and invalid input, without crashing the session.
- Three modes: interactive, one-shot and batch, with a meaningful exit status in the non-interactive modes.
- Safety: nothing the user types may ever be executed as a command.
Choosing the Arithmetic Engine
Bash's own arithmetic, $(( )) (lesson 49), only knows integers:
$ echo $(( 10 / 4 ))
2
$ echo $(( 7 / 2 * 2 ))
6
The division truncates, so 7 / 2 * 2 gives 6 instead of 7. For a calculator this is not acceptable. The standard tool for exact decimal arithmetic on Unix systems is bc ("basic calculator"), an arbitrary-precision calculator language installed on most Linux systems and on macOS. Its scale variable sets how many decimal places division and functions produce, and its numbers have no size limit:
$ printf 'scale=0\n10/4\nscale=6\n10/4\n2^64\n' | bc -l
2
2.500000
18446744073709551616
bc -l loads the math library (needed for pi, computed as 4 * a(1), the arctangent of 1 times four). The calculator therefore uses Bash for everything around the arithmetic: reading input, checking it, managing variables and printing results, and passes each checked expression to bc.
Why Not Simply Use eval or $(( ))?
The quickest calculator in Bash is a one-liner such as read -r line; echo $(( line )). It is also dangerous. Inside arithmetic expansion, Bash evaluates variable names recursively and expands array subscripts, and an array subscript may contain a command substitution:
$ x='a[$(echo INJECTED >&2)]'
$ echo "result: $(( x ))"
INJECTED
result: 0
The command inside the subscript ran. With read feeding user input into $(( )), a user could run any command with the script's permissions, a code injection vulnerability (lessons 155 and 157). eval is even more direct. Passing raw input to bc is not safe either: bc is a programming language with loops, and some versions have functions like read() or commands like quit that change the program's behavior.
The safe design is validation by tokenizing: split the input into tokens (numbers, names, operators), allow only known kinds of tokens, and build the expression for bc from those tokens alone. Anything unexpected is rejected before it reaches any interpreter.
Building the Calculator Step by Step
Step 1: The Tokenizer
The translate function reads the input from left to right. At each position it tries a series of regular expressions anchored with ^, so each one can only match at the current position:
translate() {
local rest=$1 out="" token
while [[ -n $rest ]]; do
if [[ $rest =~ ^[[:space:]]+ ]]; then
token=${BASH_REMATCH[0]}
elif [[ $rest =~ ^([0-9]+(\.[0-9]*)?|\.[0-9]+) ]]; then
token=${BASH_REMATCH[0]}
out+=$token
elif [[ $rest =~ ^[a-z_][a-z0-9_]* ]]; then
...
elif [[ $rest =~ ^[-+*/^(),] ]]; then
token=${BASH_REMATCH[0]}
out+=$token
else
error "unexpected character '${rest:0:1}'"
return 1
fi
rest=${rest:${#token}}
done
...
}
BASH_REMATCH[0]holds the text matched by the last=~test (lesson 69).- Whitespace is consumed but not copied.
- Numbers are digits with an optional decimal part, or a decimal part alone (
.5). - Names start with a lowercase letter or underscore.
- Operators form a bracket expression; the
-comes first so it is a literal character, not a range. rest=${rest:${#token}}removes the token just consumed (lesson 152), so the next iteration looks at the following character.- Anything else, such as
$, a backtick, a semicolon or a quote, stops the tokenizer with an error. Because these characters can never pass, no input can smuggle shell orbcsyntax into the expression.
Step 2: Names, Variables and Functions
A name token is either a function (sqrt, mod) or a variable. Variables live in an associative array (lesson 102), vars, and are replaced by their value in parentheses:
elif [[ $rest =~ ^[a-z_][a-z0-9_]* ]]; then
token=${BASH_REMATCH[0]}
if [[ $FUNCTIONS == *" $token "* ]]; then
out+=$token
elif [[ -v vars[$token] ]]; then
out+="(${vars[$token]})"
else
error "unknown name '$token'"
return 1
fi
FUNCTIONS is the string " sqrt mod "; testing for *" $token "* with spaces on both sides is a simple way to check membership in a word list without matching parts of words. [[ -v vars[$token] ]] tests whether the key exists. Substituting values in parentheses matters: with x = -2, the input 5 - x becomes 5 - (-2), which bc evaluates to 7. Without the parentheses it would become 5 - -2, and bc would report a syntax error, because it reads -- as its decrement operator.
Substituting values in Bash, rather than defining variables inside bc, means bc only ever sees numbers, operators and two known function names. User variable names could otherwise collide with bc keywords such as scale, length or quit.
Step 3: Evaluating with bc
The evaluate function sends three lines to bc: the definition of the mod function, the current scale, and the expression:
readonly BC_PRELUDE='define mod(a, b) { auto s, r; s = scale; scale = 0; r = a % b; scale = s; return (r); }'
...
result=$(printf '%s\nscale = %d\n(%s) / 1\n' "$BC_PRELUDE" "$scale" "$expr" | bc -l 2> "$messages")
Two details of bc shape this code:
bc's%operator depends onscale. Withscale = 6,7 % 3computes7 - (7/3)*3with six decimal places and returns a tiny number instead of 1. Themodfunction therefore setsscaleto 0 temporarily, computes the remainder, and restores the old scale.auto s, rdeclares local variables inbc.- Multiplication keeps all decimal places of its operands.
pi * 2 ^ 2would printpi's full 20 digits. Dividing the whole expression by 1, as in(%s) / 1, applies the scale to every result.
BC_LINE_LENGTH=0 is exported at the start, which tells GNU bc not to break long numbers across lines with a backslash.
Step 4: Detecting bc Errors
bc exits with status 0 even when an expression fails; it only prints a message on standard error. The function therefore saves standard error in a temporary file and treats any message, or an empty result, as a failure, translating the most common messages into friendlier ones:
if [[ -s $messages || -z $result ]]; then
local msg
msg=$(< "$messages")
rm -f "$messages"
case $msg in
*"Divide by zero"*) error "division by zero" ;;
*"scale in exponent"*) error "exponents must be whole numbers" ;;
*"Square root of a negative"*) error "square root of a negative number" ;;
*) error "invalid expression" ;;
esac
return 1
fi
bc only supports whole-number exponents: 2 ^ 0.5 produces a "non-zero scale in exponent" warning and silently returns 1. Treating warnings as errors prevents such wrong results from being displayed.
Step 5: Cleaning Up the Output
bc prints 0.5 as .5, negative halves as -.5, and with scale = 6 it prints 2.500000. The normalize function uses only parameter expansion to produce the usual form:
normalize() {
local n=$1 sign=""
if [[ $n == -* ]]; then sign=-; n=${n#-}; fi
if [[ $n == *.* ]]; then
n=${n%"${n##*[!0]}"} # strip trailing zeros
n=${n%.} # strip a trailing dot
fi
[[ $n == .* ]] && n=0$n # .5 -> 0.5
[[ $n == 0 ]] && sign="" # never print -0
printf '%s%s\n' "$sign" "$n"
}
The trailing-zero line is a classic parameter expansion idiom: ${n##*[!0]} removes everything up to the last character that is not 0, leaving just the trailing zeros, and the outer ${n%...} removes exactly those zeros from the end. Trailing zeros are only removed when the number has a decimal point, so 100 stays 100.
Step 6: Commands and Assignments
The handle function decides what a line is, using case patterns (lesson 76) in order: empty lines and comments, the commands, scale, assignments (anything containing =), and finally expressions. It returns 0 for success, 1 for an error and 10 for "quit", so the caller can tell the three apart.
For an assignment, the part before = must be a valid lowercase name and not a reserved word; the part after it is evaluated like any expression. Because evaluate runs inside $( ) here, its change to vars[ans] would be lost in the subshell, so handle sets both the variable and ans itself.
Step 7: Three Ways to Run
The main part chooses the mode:
- Arguments given: evaluate them as one line and exit with status 0 or 1.
- Standard input is a terminal (
[[ -t 0 ]]): interactive mode.read -eenables Readline, so the arrow keys,Ctrl+A/Ctrl+Eand other editing keys work;history -sadds each line to the history list so the Up arrow recalls earlier calculations.readreturns non-zero at end of input, so pressingCtrl+Dleaves the loop. - Otherwise: batch mode reads lines from the pipe or file.
|| [[ -n $line ]]also processes a last line without a trailing newline (lesson 114). The exit status is 1 if any line failed, which makes the calculator usable in scripts.
The run function wraps handle and counts errors. The loop condition run "$line" || [[ $? != 10 ]] || break reads: if the line failed, and the failure was the quit code 10, leave the loop.
The Complete Script
#!/usr/bin/env bash
#
# calc.sh - an interactive command-line calculator
#
# Usage: calc.sh interactive mode (line editing and history)
# calc.sh 'EXPRESSION' evaluate one expression and exit
# command | calc.sh evaluate one expression or command per input line
#
# Expressions: numbers with decimals, + - * / ^ and parentheses, the functions
# sqrt(x) and mod(a, b), the constant pi, the last result ans, and your own
# variables (rate = 0.18). Type "help" for the commands.
#
# Exit status: 0 success, 1 at least one expression failed, 2 bc is missing.
set -uo pipefail
command -v bc > /dev/null || { echo "calc.sh: bc is required but not installed" >&2; exit 2; }
export BC_LINE_LENGTH=0 # GNU bc: never wrap long numbers
declare -A vars=([ans]=0)
scale=6 # decimal places for division and sqrt
errors=0
# Functions available to every expression, written in bc's own language.
readonly BC_PRELUDE='define mod(a, b) { auto s, r; s = scale; scale = 0; r = a % b; scale = s; return (r); }'
readonly FUNCTIONS=" sqrt mod "
readonly RESERVED=" sqrt mod pi ans scale help vars clear quit exit "
vars[pi]=$(printf 'scale = 20; 4 * a(1)\n' | bc -l)
error() {
printf 'error: %s\n' "$*" >&2
return 1
}
# normalize NUMBER - turn bc output like "-.500000" into "-0.5"
normalize() {
local n=$1 sign=""
if [[ $n == -* ]]; then sign=-; n=${n#-}; fi
if [[ $n == *.* ]]; then
n=${n%"${n##*[!0]}"} # strip trailing zeros
n=${n%.} # strip a trailing dot
fi
[[ $n == .* ]] && n=0$n # .5 -> 0.5
[[ $n == 0 ]] && sign="" # never print -0
printf '%s%s\n' "$sign" "$n"
}
# translate EXPRESSION - check every token and replace variables by their values.
# Prints the bc expression; returns 1 (after printing an error) if the input is invalid.
translate() {
local rest=$1 out="" token
while [[ -n $rest ]]; do
if [[ $rest =~ ^[[:space:]]+ ]]; then
token=${BASH_REMATCH[0]}
elif [[ $rest =~ ^([0-9]+(\.[0-9]*)?|\.[0-9]+) ]]; then
token=${BASH_REMATCH[0]}
out+=$token
elif [[ $rest =~ ^[a-z_][a-z0-9_]* ]]; then
token=${BASH_REMATCH[0]}
if [[ $FUNCTIONS == *" $token "* ]]; then
out+=$token
elif [[ -v vars[$token] ]]; then
out+="(${vars[$token]})"
else
error "unknown name '$token'"
return 1
fi
elif [[ $rest =~ ^[-+*/^(),] ]]; then
token=${BASH_REMATCH[0]}
out+=$token
else
error "unexpected character '${rest:0:1}'"
return 1
fi
rest=${rest:${#token}}
done
[[ -n $out ]] || { error "empty expression"; return 1; }
printf '%s\n' "$out"
}
# evaluate EXPRESSION - print the result and store it in ans
evaluate() {
local expr result messages
expr=$(translate "$1") || return 1
messages=$(mktemp)
result=$(printf '%s\nscale = %d\n(%s) / 1\n' "$BC_PRELUDE" "$scale" "$expr" | bc -l 2> "$messages")
if [[ -s $messages || -z $result ]]; then
local msg
msg=$(< "$messages")
rm -f "$messages"
case $msg in
*"Divide by zero"*) error "division by zero" ;;
*"scale in exponent"*) error "exponents must be whole numbers" ;;
*"Square root of a negative"*) error "square root of a negative number" ;;
*) error "invalid expression" ;;
esac
return 1
fi
rm -f "$messages"
vars[ans]=$(normalize "$result")
printf '%s\n' "${vars[ans]}"
}
show_help() {
cat << 'EOF'
Enter an expression to evaluate it, for example:
2 + 3 * 4 (2 + 3) * 4 10 / 4 2 ^ 10
sqrt(2) mod(17, 5) pi * 2 ^ 2 ans * 2
Assign a variable: rate = 0.18 price = 250 price * (1 + rate)
Commands:
vars list variables scale N set decimal places (0-20)
clear delete your variables help show this text
quit, exit leave (or press Ctrl+D)
EOF
}
show_vars() {
local name
for name in $(printf '%s\n' "${!vars[@]}" | sort); do
printf ' %-10s = %s\n' "$name" "${vars[$name]}"
done
}
# handle LINE - process one line of input: a command, an assignment or an expression.
# Returns 0 on success, 1 on an error, 10 when the user wants to quit.
handle() {
local line=$1 name value
line=${line#"${line%%[![:space:]]*}"} # trim leading spaces
line=${line%"${line##*[![:space:]]}"} # trim trailing spaces
case $line in
'' | '#'*) return 0 ;;
help) show_help ;;
vars) show_vars ;;
clear) vars=([ans]=0 [pi]=${vars[pi]}); echo "variables cleared" ;;
quit | exit) return 10 ;;
scale | 'scale '*)
value=${line#scale}; value=${value// /}
if [[ -z $value ]]; then
echo "scale = $scale"
elif [[ $value =~ ^[0-9]+$ ]] && (( 10#$value <= 20 )); then
scale=$((10#$value)); echo "scale = $scale"
else
error "scale must be a whole number from 0 to 20"
fi
;;
*=*)
name=${line%%=*}; name=${name// /}
value=${line#*=}
if [[ ! $name =~ ^[a-z_][a-z0-9_]*$ ]]; then
error "invalid variable name '$name' (use lowercase letters, digits, _)"
elif [[ $RESERVED == *" $name "* ]]; then
error "'$name' is reserved"
else
value=$(evaluate "$value") || return 1
vars[$name]=$value
vars[ans]=$value
printf '%s = %s\n' "$name" "$value"
fi
;;
*) evaluate "$line" ;;
esac
}
# run LINE - handle one line and keep count of the errors
run() {
local rc=0
handle "$1" || rc=$?
(( rc == 1 )) && errors=$((errors + 1))
return "$rc"
}
# --- main ----------------------------------------------------------------------
if (( $# > 0 )); then # one-shot mode
run "$*"
exit $(( errors > 0 ))
fi
if [[ -t 0 ]]; then # interactive mode
echo "calc.sh - type 'help' for help, 'quit' to leave"
while IFS= read -r -e -p 'calc> ' line; do
[[ -n $line ]] && history -s -- "$line"
run "$line" || [[ $? != 10 ]] || break
done
echo
exit 0
fi
while IFS= read -r line || [[ -n $line ]]; do # batch mode: read from a pipe or file
run "$line" || [[ $? != 10 ]] || break
done
exit $(( errors > 0 ))
set -uo pipefail is used without -e on purpose: in an interactive program, a failing expression is a normal event that must be reported and survived, not a reason to exit. Every function reports failure through its return status instead, and the callers check it.
Running the Calculator
Interactive Mode
$ ./calc.sh
calc.sh - type 'help' for help, 'quit' to leave
calc> price = 250
price = 250
calc> price * 1.18
295
calc> 1/0
error: division by zero
calc> quit
Batch Mode
A file of calculations and commands, session.txt, exercises every feature. The results and the errors appear in order (errors go to standard error):
$ ./calc.sh < session.txt; echo "status $?"
| Input | Output |
|---|---|
2 + 3 * 4 | 14 |
(2 + 3) * 4 | 20 |
10 / 4 | 2.5 |
2 ^ 10 | 1024 |
1 / 3 | 0.333333 |
-1/2 | -0.5 |
sqrt(2) | 1.414213 |
mod(17, 5) | 2 |
pi * 2 ^ 2 | 12.56637 |
ans / 2 | 6.283185 |
price = 250 | price = 250 |
rate = 0.18 | rate = 0.18 |
price * (1 + rate) | 295 |
total = ans * 3 | total = 885 |
scale 2 | scale = 2 |
22 / 7 | 3.14 |
1 / 0 | error: division by zero |
2 ^ 0.5 | error: exponents must be whole numbers |
sqrt(-4) | error: square root of a negative number |
2 + | error: invalid expression |
5 $ 3 | error: unexpected character '$' |
discount * 2 | error: unknown name 'discount' |
Price = 3 | error: invalid variable name 'Price' (use lowercase letters, digits, _) |
pi = 3 | error: 'pi' is reserved |
$(touch /tmp/pwned) | error: unexpected character '$' |
a[$(touch /tmp/pwned)] | error: unknown name 'a' |
2 ^ 100 | 1267650600228229401496703205376 |
1 - 1 | 0 |
A few results deserve a comment:
pi * 2 ^ 2shows that^binds more tightly than*, and the result has five decimals becausenormalizeremoved the sixth, which was a zero.sqrt(2)gives1.414213:bctruncates to the scale rather than rounding, so the true value 1.4142135... is cut after six digits.- The two injection attempts are stopped by the tokenizer, and
/tmp/pwnedwas never created. 2 ^ 100showsbc's arbitrary precision; Bash's 64-bit integers would overflow here.
The vars command lists all variables, including the built-in ones, and clear removes the user's variables:
calc> vars
ans = 3.14
pi = 3.14159265358979323844
price = 250
rate = 0.18
total = 885
calc> clear
variables cleared
calc> vars
ans = 0
pi = 3.14159265358979323844
Because the session contained errors, the exit status is 1. In batch mode, a script can use the calculator and check whether every line succeeded.
One-Shot Mode
$ ./calc.sh '(1 + 2' ; echo "status $?"
error: invalid expression
status 1
$ ./calc.sh 'pi * 2 ^ 2'; echo "status $?"
12.56637
status 0
Quoting the expression keeps the shell from interpreting *, ( and spaces before the calculator sees them.
Ideas for Extending the Project
The structure makes extensions straightforward, because each concern lives in one function:
- More functions: add
abs,minormaxby defining them inBC_PRELUDEand listing them inFUNCTIONSandRESERVED; the tokenizer then accepts them automatically. - Persistent variables: save
varsto a file in~/.configon exit and load it on start, validating each line exactly like user input. - A history file:
history -randhistory -wwithHISTFILEset make the Up arrow remember calculations between sessions. - Tests: the batch mode makes the calculator easy to test with Bats (lesson 185): feed a line, check the output and the exit status, as in lesson 187.