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:
- If it reads a case-insensitive equivalent of “Y” or “YES”, the function returns true.
- If it reads a case-insensitive equivalent of “N” or “NO”, the function returns false.
- If it reads the empty string, the function returns the specified default value. The default value also determines whether the prompt says “Y/n” or “y/N”.
- If anything else happens, the function returns false (independently of the default value).
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