POSIX Shell Password – How to Ask for a Password in POSIX-Compliant Shell

passwordposixscriptingshell

When I want to ask for a password in a bash script, I do that :

read -s

…but when I run bash in POSIX mode, with sh, the -s option is rejected:

$ read -s
sh: 1: read: Illegal option -s

How do I securely ask for an input with a POSIX-compliant command ?

Best Answer

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.