Linux Basic — yes/no Confirmation

less than 1 minute read

Yes/No Confirmation

A canonical confirmation prompt insists on a clear response and offers a default. Here’s a compact reusable function.


confirm() Function

confirm() {
    local prompt default reply
    prompt="$1"; default="$2"
    while true; do
        read -rp "$prompt" 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 "Proceed? [Y/n] " "y"; then
    echo "Proceeding"
else
    echo "Aborting"
fi
  • reply=${reply:-$default} ensures the default applies on empty input
  • ${reply,,} lowercases the answer (Bash >=4). For POSIX, use tr.

Single-Key Confirmation

read -n1 -rp "Delete file? [y/N] " c
echo
if [[ "${c,,}" == "y" ]]; then
    rm file
fi

This is convenient but less explicit than typing yes or no.


Defaults and Timeouts

Combining -t with a default protects unattended runs:

if read -t 5 -rp "Continue? [Y/n] " ans; then
    ans=${ans:-Y}
else
    ans=Y  # timeout default
fi

Be explicit with defaults in automation-friendly scripts.


Next → Practice Exercises

Updated: