Read in passwords with bash


24th of March 2005

This has taken me some time to figure out because I couldn't find anything on Google. I think the problem was that I didn't know what to look for.

If you have a bash script that asks the user to enter their username and password you use the read function in sh. But when you read in the password you don't want it to show on the screen what you're writing. Someone could be leaning over your shoulder. Python has a similar standard library module called getpass which works like this:

 >>> from getpass import getpass
 >>> p = getpass("Password please: ")
 Password please: 
 >>> print "Your password is", len(p), "characters long"
 Your password is 5 characters long

That's fine if you do this via Python; but I needed to do it in one of my bash scripts. Here's how to do it:

 #!/bin/bash
 read -p "Username: " uname
 stty -echo
 read -p "Password: " passw; echo
 stty echo

Now, hopefully this will help other people who get stuck with the same problem.



Comment

27 comments so far Show all 27 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.