I want to secure the execution of a program with a password. How can I ask the user to enter a password without echoing it?
-
1Voting to close as unclear, please specify how you want password input to be different than other inputs. No echoing asked at: http://stackoverflow.com/questions/3980668/how-to-get-a-password-from-a-shell-script-without-echoing – Ciro Santilli OurBigBook.com Jun 29 '16 at 21:26
3 Answers
This command will read into var pw
from stdin (with echo disabled):
IFS= read -r -s -p 'Password: ' pw
echo
The last echo
adds a newline to the terminal output (otherwise next commands would appear in the same line as the Password:
prompt.
Unsetting IFS allows for leading and trailing whitespace in passwords (which may be supported in some environments, so best to support it during your script's input of the user credentials).
If you want, you can verify that the above works by running it with a fake password that includes whitespace and then printing the variable's contents into hexdump:
printf '%s' "$pw" | hexdump -C
Note: don't use with real passwords as it dumps to the console!
HT: Ron DuPlain for this additional information on IFS unsetting.

- 3,989
- 3
- 32
- 56

- 18,997
- 3
- 42
- 58
-
3Are there any disadvantages if I used this instead of the accepted answer? – Tristian Oct 19 '12 at 01:46
-
7@Triztian yes, the above will probably only work in Bash. The accepted answer should work on most (all?) shells. – jberryman Oct 22 '12 at 14:53
If you need to grab a passwd to supply as a paramter to a program, then unicorns advice to just turn off the echo is good.
Having a passwd check in the script doesn't work - if the user can execute the bash script they also have permission to read it and see the passwd.
If you want to only allow people with a passwd to run a program then the secure way is to create a new user account that owns the program and have a script that uses 'sudo' to run the program as that user - it will prompt for the users passwd in a secure way.

- 94,801
- 28
- 188
- 263
-
2One might precompute the checksum of the password and store *it* in the script instead of the plaintext and test the checksum of the input against that. It can still be broken, though, but less easily. – Dennis Williamson Apr 16 '10 at 18:11
-
1In which case you just simply copy the script to somewhere you have write permission, and remove the check. – Martin Beckett Apr 16 '10 at 18:21