Wednesday, May 9, 2007

Reading passwords in shell script


There is an option with "read" to read password, here is a small shell script stating that.
When the script prompt to enter the password, and user type the password, it won't be displayed on the screen.

$ cat passwwd.sh
#!/bin/sh

ACTUAL="perftest"
read -s -p "Password: " enteredpass
echo ""

[ "$enteredpass" == "$ACTUAL" ] && echo "Accepted" || echo "Sorry"

This can be achieved using "stty" also as shown below:

old_set=`stty -g` #store original state of stty
echo -n "Password: "
stty -echo #turn off echoing
read password
stty echo #To restore the echoing
echo ""
echo "You entered $password"
stty $old_set #set original state

No comments:

© Jadu Saikia www.UNIXCL.com