Blog Linux

read input without echo in bash

I have a script that needs to be deployed in different environment as most scripts are. This script requires asking for userid, tnsname and password during deployment. I tried to use READ but it echoes the password on the screen as soon as I type it. So how can we hide the password? Here's how.


echo "TNSNAME : c"
read TNSNAME

echo "Enter User Name : c"
read DBUSER

echo "Enter Password : c"
#hear is the meat
stty -echo
read DBPASS
stty echo
echo "" #new line

echo $DBUSER"/"$DBPASS"@"$TNSNAME

As you see, I used stty -echo before the read DBPASS. It suppresses the displaying of what you type so that no one can see the password. I added the stty echo to put the display back after getting the password.

Depending on the Unix/Linux flavor you are using, the script above may or may not work. So you can try the one below. It is much simpler but did not work for HP UX.

read -s "TNSNAME : " TNSNAME
read -s "Enter User Name : " DBUSER
read -sp "Enter Password : " DBPASS

Neat and straightforward. Unfortunately, it work mostly for Linux only. Hats of to peterbe(http://www.peterbe.com/plog/passwords-with-bash) where I got this.

By the way, did you notice the c on my echo commands? That's to suppress the linefeed/newline character so that you'll input the values next to the prompt.