How can I write Bash Code for Hiding Password Or convert into '*' user input will be in string so no spaces, and change or hide password String.
Asked
Active
Viewed 4,349 times
8
-
1A string is a string even if it contains spaces, and passwords often contain spaces... – Kusalananda Dec 10 '18 at 20:33
-
Oooph, tough call for me on VTC here. The target Q does have an answer that would print asterisks, as asked (in a comment) in this question, but it doesn't handle backspaces as also hinted at here. I'll VTC because it's a good duplicate otherwise, but if this question is edited to incorporate new requirements, it could become separate. – Jeff Schaller Dec 11 '18 at 13:54
2 Answers
13
Use read -s
to not echo the input, i.e. show nothing when the user types the password:
read -p 'Password? ' -s password
echo Your password is "$password".

choroba
- 47,233
-
-
2Not so easily. You can
read -n1
and display the asterisk yourself, though. – choroba Dec 10 '18 at 17:04 -
1@choroba: I've just tested a bit, and -- it looks like using
read -n1
for this has some sharply negative consequences, e.g. in that it's a lot of work to try to support backspace. – ruakh Dec 11 '18 at 00:20 -
@AlphaCoder It is not idiomatic in Unix to display even the length of a password at the CLI. – chrylis -cautiouslyoptimistic- Dec 11 '18 at 08:00
-
11
You can use the systemd-ask-password
, the password will displayed as asterisks while typing.
Format: (systemd-ask-password --help
)
systemd-ask-password [OPTIONS...] MESSAGE
e,g:
PASSWORD=$(systemd-ask-password "Please type your Password:")
Please type your Password: ***********

GAD3R
- 66,769
-
1When I try this, I get
bash: systemd-ask-password: command not found
. . . – ruakh Dec 11 '18 at 00:15 -