Ask for a password in POSIX-compliant shell?
read_password() {
REPLY="$(
# always read from the tty even when redirected:
exec < /dev/tty || exit # || exit only needed for bash
# save current tty settings:
tty_settings=$(stty -g) || exit
# schedule restore of the settings on exit of that subshell
# or on receiving SIGINT or SIGTERM:
trap 'stty "$tty_settings"' EXIT INT TERM
# disable terminal local echo
stty -echo || exit
# prompt on tty
printf "Password: " > /dev/tty
# read password as one line, record exit status
IFS= read -r password; ret=$?
# display a newline to visually acknowledge the entered password
echo > /dev/tty
# return the password for $REPLY
printf '%s\n' "$password"
exit "$ret"
)"
}
Note that for those shells (mksh) where printf
is not builtin, the password will appear in clear in the ps
output (for a few microseconds) or may show up in some audit logs if all command invocations with their parameters are audited.
read -s
is not in POSIX. If you want to be POSIX-compliant use the stty -echo
. stty
and its echo
parameter are defined in POSIX.
#!/bin/bash
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"
This will work on all shells that conform to POSIX.
Source