Prompting for a Password
Problem
You need to prompt the user for a password, but you don’t want it echoed on the screen.
Solution
read -s -p "password: " PASSWD printf "%b" "\n"
Discussion
The -s option tells the read command
not to echo the characters typed (s is for silent)
and the -p option says that
the next argument is the prompt to be displayed prior to reading
input.
The line of input that is read from the user is put into the
environment variable named $PASSWD.
We follow read with a printf to print out a newline. The printf is necessary because read -s turns off the echoing of characters.
With echoing disabled, when the user presses the Enter key, no newline
is echoed and any subsequent output would appear on the same line as the
prompt. Printing the newline gets us to the next line, as you would
expect. It may even be handy for you to write the code all on one line
to avoid intervening logic; putting it on one line also prevents
mistakes should you cut and paste this line elsewhere:
read -s -p "password: " PASSWD ; printf "%b" "\n"
Be aware that if you read a password into an environment variable it is in memory in plain text, and thus may be accessed via a core dump or /proc/core. It is also in the process environment, which may be accessible by other processes. You may be better off using certificates with SSH, if possible. In any case, it is wise to assume that root and possibly other users on the machine may gain access to the password, so you should handle the situation accordingly. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access