Confirmation prompts for shell scripts

The source code of Arch Linux’s pacman defines a function that prompts the user for confirmation. It handles the answer as follows:

Function “question” in src/pacman/util.c

I present different functions that emulate this behavior in POSIX shell.

Default yes

To have yes as the default answer, use this:

A return value of 0 means true. Anything else means false.

The function doesn’t work if stdin is not the terminal (e.g. when reading from a file). But it does still work if stdout is redirected, as the prompt is printed to stderr instead of stdout.

Default no

To have no as the default answer, use this:

Flexible defaults

To specify a default answer when calling the function, use this:

If it reads the empty string, the function replaces it with the default answer. The default answer is handled as in confirm_y. So if no default answer is specified, the function assumes yes.

Custom question and flexible defaults

To also specify a custom question, use this:

If no question is specified, the function assumes “Continue?”.

EOF