On this page
- How do I ask a question and store the answer?
- How do I read a password without showing it?
- How do I add a timeout or limit the input length?
- How do I write a reliable yes or no confirmation?
- How do I offer a menu of choices?
- How do I parse command line options with getopts?
- How can a script read from a pipe as well as the keyboard?
- How do I validate what the user typed?
- Questions
How do I ask a question and store the answer?
Call the read builtin with a prompt and a variable name. Always include -r so backslashes in the answer are kept as typed:
#!/usr/bin/env bash
read -r -p "Domain for the new site: " domain
read -r -p "Owner account [deploy]: " owner
owner="${owner:-deploy}"
echo "Creating $domain for $owner"The default in square brackets is just text in the prompt; the ${owner:-deploy} line makes it real when the user presses Enter without typing. Given several variable names, read splits the line on spaces: read -r first rest puts the first word in first and everything else in rest. With no name at all, the line lands in the special variable REPLY.
How do I read a password without showing it?
Add -s (silent), and print a newline afterwards because the Enter key is not echoed either:
read -r -s -p "Database password: " db_pw; echo
read -r -s -p "Repeat password: " db_pw2; echo
if [[ "$db_pw" != "$db_pw2" || -z "$db_pw" ]]; then
echo "passwords do not match or are empty" >&2
exit 1
fi
printf '%s' "$db_pw" | sudo tee /etc/myapp/db.pass >/dev/null
sudo chmod 600 /etc/myapp/db.pass
unset db_pw db_pw2Never pass secrets as command line arguments to other programs where you can avoid it: arguments are visible to every user through ps. Write them to a file with mode 600 or pipe them on standard input, as above, and clear the variables once done. For generating a random password instead of asking for one, openssl rand -base64 24 is available on every image.
How do I add a timeout or limit the input length?
-t sets a timeout in seconds, after which read fails with a status above 128; -n returns after a set number of characters, so the user does not need to press Enter:
if read -r -t 15 -p "Restart nginx now? [y/N] " -n 1 answer; then
echo
else
echo; echo "no answer, skipping"
answer=n
fi
read -r -e -i "/var/www/app.example.net" -p "Web root: " webrootThe -e flag turns on Readline editing (arrow keys and Tab completion of file names), and -i pre-fills the line with a suggestion the user can edit. Both only work in an interactive terminal. Timeouts are useful in scripts that someone may start and walk away from, so a forgotten prompt does not block a maintenance window.
How do I write a reliable yes or no confirmation?
Wrap the question in a function that loops until the answer is clear, and treat anything unexpected as no:
confirm() {
local reply
while true; do
read -r -p "${1:-Continue?} [y/n] " reply || return 1
case "${reply,,}" in
y|yes) return 0 ;;
n|no|"") return 1 ;;
*) echo "please answer y or n" ;;
esac
done
}
if confirm "Delete logs older than 30 days?"; then
sudo find /var/log/myapp -name "*.log" -mtime +30 -delete
fiThe || return 1 handles Ctrl+D (end of input) as a refusal. Lowercasing the reply with ${reply,,} accepts Y, YES and yes alike. A confirmation like this belongs in front of every destructive step: deleting files, dropping databases or reinstalling packages. The case syntax is covered in if, else and case in Bash.
How do I offer a menu of choices?
The select loop prints a numbered list, reads a number and sets a variable to the chosen item:
PS3="Pick a PHP version: "
select ver in 8.3 8.2 quit; do
case "$ver" in
quit) exit 0 ;;
"") echo "invalid choice" ;;
*) echo "installing PHP $ver"; break ;;
esac
donePS3 sets the prompt shown under the list. An invalid number leaves the variable empty, which the empty pattern catches. select loops until break, so a valid pick must end the loop explicitly. Fill the list from an array (select f in "${files[@]}") to let the user choose among files or services found at run time. The version numbers above are just labels; check what your distribution actually offers before installing.
How do I parse command line options with getopts?
getopts handles short options such as -d example.net -v in any order, including combined forms like -vf:
#!/usr/bin/env bash
usage() { echo "usage: ${0##*/} [-v] [-u user] -d domain" >&2; exit 2; }
verbose=0; owner="deploy"; domain=""
while getopts ":vu:d:h" opt; do
case "$opt" in
v) verbose=1 ;;
u) owner="$OPTARG" ;;
d) domain="$OPTARG" ;;
h) usage ;;
:) echo "-$OPTARG needs a value" >&2; usage ;;
\?) echo "unknown option -$OPTARG" >&2; usage ;;
esac
done
shift $(( OPTIND - 1 ))
[[ -n "$domain" ]] || usage
(( verbose )) && echo "domain=$domain owner=$owner extra=$*"In the option string, a letter followed by a colon takes a value, delivered in OPTARG. The leading colon switches on quiet error mode so your own messages appear. After the loop, shift removes the parsed options and leaves the remaining arguments in "$@". getopts does not understand long options such as --domain; for those, loop over "$@" with case yourself or use the getopt program from util-linux.
How can a script read from a pipe as well as the keyboard?
Check whether standard input is a terminal with [[ -t 0 ]]. If it is not, data is being piped in and prompting makes no sense:
if [[ -t 0 ]]; then
read -r -p "Paste a hostname: " host
else
read -r host
fi
echo "checking $host"
getent ahosts "$host" | head -n 1Now echo app.example.net | ./check.sh and an interactive run both work. To process every piped line, use the while IFS= read -r loop from for, while and until loops. Scripts started from cron, a systemd timer or CI never have a terminal, so they must get every value from options, environment variables or a config file; make the script fail with a clear message rather than hang at a prompt.
How do I validate what the user typed?
Check the answer against a pattern straight away and ask again on bad input, so later commands never see garbage:
while true; do
read -r -p "SSH port (1024-65535): " port
if [[ $port =~ ^[0-9]+$ ]] && (( port >= 1024 && port <= 65535 )); then
break
fi
echo "not a valid port"
done
read -r -p "Domain: " domain
[[ $domain =~ ^[a-z0-9.-]+\.[a-z]{2,}$ ]] || { echo "bad domain" >&2; exit 1; }Validating before arithmetic also matters for safety: Bash evaluates variable contents inside (( )), so an unchecked answer can run unexpected expressions. The regex test runs first above for that reason. If you change the SSH port, also open it in your firewall as shown in the firewall rules tutorial before restarting the SSH service.
Questions about Read user input in Bash
Why does read ignore my backslashes?
Without -r, read treats a backslash as an escape and removes it. Always use read -r unless you need line continuation.
Why does my prompt not appear when I pipe input?
The -p prompt is only printed when input comes from a terminal. That is intended: piped data needs no prompt.
Can I read a single key press, like Press any key?
Yes: read -r -s -n 1 -p "Press any key to continue". Add echo afterwards to move to a new line.
How do I pass answers to a script automatically?
Pipe them in, one per line: printf '%s\n' example.net deploy | ./setup.sh. Better still, give the script options so it does not need answers.
Is read safe for secrets on a shared server?
Silent reading hides the input from the screen, and the value never appears in ps. Avoid writing it to logs or using set -x around it, since tracing prints the value.