Hide password entry in Bourne/bash shell script

Posted December 15, 2003 by Rex in Bourne shell scripting

Common practice for inputing passwords is to read the text without displaying it on the screen. The UNIX Bourne shell does not have this functionality as a command, but a combination of commands will make this work.


The stty command sets numerous terminal parameters including whether or not characters should be echoed to the terminal. To turn off echoing, the command stty -echo can be used. Any subsequent user input (including commands typed at the shell) will not be echoed. To restore the echoing, use stty echo. However, it is poor programming to make the assumption that echo is on. In some cases, echoing of characters is done at the local terminal (in which case we cannot prevent echoing passwords) and the result of the second command will be that every character typed will appear twice. To avoid this, a neat stty trick is used in which the original state of stty is stored before the stty change and restored after the read. The following code will read a password into the variable secret:

stty_orig=`stty -g`
stty -echo
read secret
stty $stty_orig

The Conversation

Follow the reactions below and share your own thoughts.