Print asterisk instead of password (Bash)

OS : RHEL 6.5
Shell : Bash

With the following bash shell script, when I enter password, it won't be printed in the screen.
But, I would like Asterisk character to be printed instead of the real characters. Any idea how ?

$ cat pass.sh
echo "Enter the username"
read username

echo "Enter password"
stty -echo
read password
stty echo

Executing :

$ ./pass.sh
Enter the username
apuser
Enter password
$

Hello John K,

Kindly use read -p option for same, it should do the trick.

Thanks,
R. Singh

1 Like

I think that the -p flag of read takes the next item as a prompt, so you might have:-

$ cat pass.sh
echo "Enter the username"
read username

stty -echo
read -p "Enter password:- " password
stty echo
echo           # Force new-line because otherwise
               # the cursor is left at the end of the prompt and may confuse any subsequent output.

To display one * for every key press will be more tricky. You would need to read the input 1 character at a time and display the * , building up your overall password variable as you go. No doubt you would also want to handle mistakes in the input, so you would have to allow a backspace character and both delete an * from the screen (making sure that you don't start deleting the prompt) but also remove the last character from the variable you are building up.

Is it really worth this much effort? A telnet or ssh login prompt does not go to these lengths, and it's of limited value to the user anyway.

Those horrible project management phrases are clanging in my head - cost justification; business need; supportability; ..........

Robin

1 Like

Hi.

See also:

ledit (1)            - line editor, version 2.03
rlfe (1)             - "cook" input lines for other programs using readline
rlwrap (1)           - readline wrapper

For some details on readline, see man page for:

readline (3readline) - get a line from a user with editing

Best wishes ... cheers, drl