Build an Interactive Calculator

Su Suriya Ravichandran Updated 06 Dec 2026
17 min read ·Lesson 192 of 205

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:

  1. Decimal arithmetic. 10 / 4 must give 2.5, not 2.
  2. Operators and parentheses: + - * / ^ with the usual precedence, and ( ) for grouping.
  3. Functions and constants: sqrt(x), mod(a, b) for the remainder, and pi.
  4. Variables: rate = 0.18 stores a value; ans always holds the last result.
  5. Commands: help, vars, scale N (number of decimal places), clear, quit.
  6. Helpful errors for division by zero, unknown names and invalid input, without crashing the session.
  7. Three modes: interactive, one-shot and batch, with a meaningful exit status in the non-interactive modes.
  8. 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 or bc syntax 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 on scale. With scale = 6, 7 % 3 computes 7 - (7/3)*3 with six decimal places and returns a tiny number instead of 1. The mod function therefore sets scale to 0 temporarily, computes the remainder, and restores the old scale. auto s, r declares local variables in bc.
  • Multiplication keeps all decimal places of its operands. pi * 2 ^ 2 would print pi'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 -e enables Readline, so the arrow keys, Ctrl+A/Ctrl+E and other editing keys work; history -s adds each line to the history list so the Up arrow recalls earlier calculations. read returns non-zero at end of input, so pressing Ctrl+D leaves 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 $?"
InputOutput
2 + 3 * 414
(2 + 3) * 420
10 / 42.5
2 ^ 101024
1 / 30.333333
-1/2-0.5
sqrt(2)1.414213
mod(17, 5)2
pi * 2 ^ 212.56637
ans / 26.283185
price = 250price = 250
rate = 0.18rate = 0.18
price * (1 + rate)295
total = ans * 3total = 885
scale 2scale = 2
22 / 73.14
1 / 0error: division by zero
2 ^ 0.5error: exponents must be whole numbers
sqrt(-4)error: square root of a negative number
2 +error: invalid expression
5 $ 3error: unexpected character '$'
discount * 2error: unknown name 'discount'
Price = 3error: invalid variable name 'Price' (use lowercase letters, digits, _)
pi = 3error: 'pi' is reserved
$(touch /tmp/pwned)error: unexpected character '$'
a[$(touch /tmp/pwned)]error: unknown name 'a'
2 ^ 1001267650600228229401496703205376
1 - 10

A few results deserve a comment:

  • pi * 2 ^ 2 shows that ^ binds more tightly than *, and the result has five decimals because normalize removed the sixth, which was a zero.
  • sqrt(2) gives 1.414213: bc truncates 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/pwned was never created.
  • 2 ^ 100 shows bc'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, min or max by defining them in BC_PRELUDE and listing them in FUNCTIONS and RESERVED; the tokenizer then accepts them automatically.
  • Persistent variables: save vars to a file in ~/.config on exit and load it on start, validating each line exactly like user input.
  • A history file: history -r and history -w with HISTFILE set 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Build an Interactive Calculator and get answers drawn from it.

Signed-in readers only.