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" " "
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.
Some older scripts may use stty
-echo
to disable the screen echo while a password is being
entered. The problem with that is this if the user breaks the script,
echo will still be off. Experienced users will know to type stty sane
to fix
it, but it’s very confusing. If you still need to use this method, set
a trap to turn echo back on when the script terminates. See Trapping Interrupts.
18.116.67.22