Here’s the classic, bullet‑proof way to pause a Bash script and ask the user if it’s OK to move on.
#!/usr/bin/env bash
confirm() {
# $1 = prompt message (optional)
local prompt="${1:-Are you sure you want to continue? [y/N]} "
local reply
# -r : don’t let backslashes escape anything
# -n1: read only one character
# -s : don’t echo the character (silent)
read -r -n1 -p "$prompt" reply
echo # (adds the trailing newline)
case "$reply" in
[yY]) return 0 ;; # success
*) return 1 ;; # anything else is “no”
esac
}
########################################################
# Example usage
########################################################
echo "Step 1 finished ✔️"
if confirm "Go to step 2? [y/N]"; then
echo "Running step 2..."
# … your code here …
else
echo "Aborted by user."
exit 1
fi
What’s happening?
• read -r -n1 -p "$prompt" reply
‑ -r keeps raw input.
‑ -n1 grabs a single character, so the user just presses y or n.
‑ -p shows the prompt without needing a separate echo.
• echo after read drops us onto a new line (purely cosmetic).
• The case statement tests the answer; only y/Y counts as “yes.”
Variations & Tips
-
Case‑insensitive extended pattern:
[[ $reply =~ ^[Yy]$ ]] && … # regex version
-
Force an explicit yes/no loop:
while true; do
read -rp "Proceed? (yes/no) " ans
case "$ans" in
yes|y|Y ) break ;; # continue the script
no|n|N ) exit 1 ;;
* ) echo "Please answer yes or no." ;;
esac
done
-
Non‑interactive mode (CI/CD pipelines):
Let users bypass the prompt with a flag or env var:
if [[ $AUTO_YES == 1 ]] || [[ $1 == "-y" ]]; then
echo "Auto‑approved."
else
confirm "Continue? [y/N]" || exit 1
fi
-
Use select for multi‑choice menus:
PS3="Pick an option: "
select opt in Backup Restore Quit; do
case $REPLY in
1) backup;; 2) restore;; 3) break;;
*) echo "Invalid.";;
esac
done
That’s all you need to gracefully ask for confirmation in Bash. Happy scripting! 🎉