Answers:
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"
)"
}
请注意,对于printf
未内置的那些shell(mksh),ps
如果对所有命令调用及其参数进行了审核,则密码将在输出中清晰显示(几秒钟),或在某些审核日志中显示。
cat
+ Heredoc可以更安全地替代printf
吗?
REPLY="$(...)"
不损害(除SE语法高亮显示),但不是必需的
stty
设置。
read -s
不在POSIX中。如果要兼容POSIX,请使用stty -echo
。stty
及其echo
参数在POSIX中定义。
#!/bin/bash
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"
这将在所有符合POSIX的shell上工作。
stty echo
-以防用户感到困惑并在本read PASSWORD
节中碰到control-C 。