3

I'm writing a script in Bash that prompts the user for a password and I need the typed text to not show, as when you enter an ssh password.

Does anyone have the solution for this?

  • 2
    Same question on SO – SuperStormer Aug 10 at 23:19
  • 1
    /Which/ password? If the password is being captured solely to be passed into some other utility program, there may be better ways of providing it! – Phill W. Aug 12 at 14:50
18

You may add -s to your read command, so it would become:

read -r -s password

From read --help:

-r    do not allow backslashes to escape any characters
-s    do not echo input coming from a terminal
| improve this answer | |
  • 3
    Also avoid stripping leading and trailing whitespace: IFS= read -rs password – wjandrea Aug 11 at 13:20
9

In order for the terminal not to show typed text, echo needs to be turned off. The command stty -echo does this. To return to normal, run stty echo.

Example:

#!/bin/sh
printf "Enter password: "
stty -echo
read -r password
stty echo
echo ""
echo "password=$password"

If, due to a typo or other error, the script fails to restore echo, run reset to recover.

The above script, including the use of stty and read, is POSIX compatible. This means it will work with both bash and /bin/sh.

| improve this answer | |
  • 1
    Is read -s SIGINT safe? I frequently find myself resorting to stty sane after Ctrl-Cing badly-behaved programs, and this script could get wedged in -echo. – chrylis -cautiouslyoptimistic- Aug 11 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.