Bash Scripting — Interactive Scripts

1 minute read

What Are Interactive Scripts?

So far, most of our scripts have taken their input from arguments or files. But sometimes you need your script to have a conversation with the user — ask questions, present menus, validate answers, and confirm dangerous actions before proceeding.

This chapter covers everything you need to build user-friendly interactive scripts in Bash.


What You’ll Learn

Topic What It Covers
read with Prompts read -p, -s, -t, -n, -r
Input Validation Loops Retry loops, numeric checks, range & file validation
select Statement Menus, REPLY, PS3, case dispatch
getopts Option Parsing Flags, OPTARG, OPTIND, long-options workaround
yes/no Confirmation Pattern Safe prompts, --force flag, single-keypress
Practice Exercises 5 hands-on challenges

Why Interactive Scripts Matter

Think about a deployment script. You wouldn’t want it to blindly delete a production database without asking first, right? Interactive patterns give your scripts guardrails:

  • Prompts gather missing information at runtime.
  • Validation prevents garbage-in, garbage-out.
  • Menus guide users through complex choices.
  • Option parsing makes scripts feel like real CLI tools.
  • Confirmations protect against accidental destruction.

Quick Taste

Here’s a tiny interactive script that combines several patterns from this chapter:

#!/usr/bin/env bash
set -euo pipefail

read -rp "Enter your project name: " project
[[ -z "$project" ]] && { echo "Name cannot be empty."; exit 1; }

read -rp "Create directory '$project'? [y/N]: " confirm
if [[ "${confirm,,}" == "y" ]]; then
    mkdir -p "$project"
    echo "✅ Created '$project'"
else
    echo "Aborted."
fi
Enter your project name: my-app
Create directory 'my-app'? [y/N]: y
✅ Created 'my-app'

By the end of this chapter, you’ll be building scripts far more sophisticated than this.


Prerequisites

You should be comfortable with:

  • Variables and quoting (Chapter 7)
  • Conditionals — if, [[ ]] (Chapter 12)
  • Loops — while, for (Chapter 14)
  • Functions (Chapter 17)

Let’s Begin

Start with read with Prompts →

Happy scripting! 🎉

Updated: