Secure Keyboard Input in BASH Scripts

Secure keyboard input in BASH 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.

Standard user input in bash

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:

$ vi

this will be the content for our file:

echo "Type your password, please:"
read PASS
echo "You just typed: $PASS"

Save the file (press Esc, then type :wq) and make it executable:

$ chmod a+rx

Now we can run the script and see how it works:

$ ./
Type your password, please:
You just typed: mypass

Works great, but seeing the typed password is not ideal. In a real world example I wouldn’t be printing the password back either.

Secure keyboard input in bash

Turns out, read function supports this scenario – just update the script to this:

read -s PASS

-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:

$ ./
Type your password, please:
You just typed: mypass

Pretty cool, huh?

See Also

  • Bash scripts
  • Math in bash scripts

Keep Learning with Me

Follow me on Facebook and Twitter or jump into Telegram chat!:
Recommended Software
I use Brave browser, it's awesome: Brave Browser I'm also a fan of SetApp for macOS: SetApp for macOS
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!
Recent Articles
18 Jun 2021

CentOS 8.4 Released

17 Jun 2021

yum/dnf Package Manager Basics

07 Jun 2021


Recent Tweets