Bash

Confirm Prompt (y/n)

admin by @admin ADMIN
4m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A reusable yes/no prompt with a configurable default and a single-keystroke read. Returns 0 for yes, non-zero for no.
Bash
Raw
confirm() {
    local prompt="${1:-Are you sure?}" default="${2:-n}"
    local hint
    case "${default,,}" in
        y|yes) hint="[Y/n]" ;;
        *)     hint="[y/N]" ;;
    esac
    local reply
    while true; do
        read -r -p "$prompt $hint " reply
        reply="${reply:-$default}"
        case "${reply,,}" in
            y|yes) return 0 ;;
            n|no)  return 1 ;;
            *) echo "Please answer yes or no." ;;
        esac
    done
}

if confirm "Delete /var/log/myapp/*?" "n"; then
    rm -rf /var/log/myapp/*
fi
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.