Secure keyboard input in BASH
I needed to create a very simple bash script that required a password to be provided using keyboard and then used further in the script. Turns out, there’s just a way to do it with the bash built-in function called read.
Here’s how a normal user input works: you invoke read function, pass it a variable name. A user is prompted for input by the bash script, and when input is provided it’s shown (echoed) back into terminal – so you can see what you type.
First, let’s create the script:
this will be the content for our file:
Save the file (press Esc, then type :wq) and make it executable:
Now we can run the script and see how it works:
Works great, but seeing the typed password is not ideal. In a real world example I wouldn’t be printing the password back either.
Turns out, read function supports this scenario – just update the script to this:
-s is obviously short for secure.
Save the script and run it again, this time typing will not show, but later command should output our input just fine:
Pretty cool, huh?