Hide password entry in Bourne/bash shell script

Contributor Icon Contributed by Rex Date Icon December 15, 2003  
Tag Icon Tagged: 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

Previous recipe | Next recipe |
 
  • Anonymous
    instead you can use -s option with read to hide the value like password

    read -s secret
  • qmchenry
    Neat trick! Beware that this is OS dependent. It works on all the Linux flavors I've tried but not a Solaris 8 system. If you are writing a script to run on many platforms, the old school method above may be more generic. But if writing a script for a specific system, this is a much slicker method. Thanks for sharing!
  • sttyecho
    I also add the protection for the interruptions:

    trap "stty echo ; exit" 1 2 15
    stty -echo
    read password
    stty echo
    trap "" 1 2 15

    If the user press Ctrl+C in the password prompt, the normal stty mode will be restored
  • qmchenry
    Awesome! I've never used trap before, but I'll be using it from now on. That's a great solution to a very annoying problem. Thanks for sharing! Use of the trap command would make a great recipe..

    Q
  • Anonymous
    One more thing (OS and shell-dependent):
    use closing redirection in the stty command:
    stty -echo >&- 2>&-

    This helps to avoid obsolete "No terminal" message in the scripts.
blog comments powered by Disqus