How To Hide User Input In The Bash Script

Usually, if we create a bash script to ask the user for input we use the command called read. The command will display input from user to terminal so a user can read it in the monitor. What about if we want to create a bash script to ask the user to input the password? It is very dangerous if someone sees the password when the user types it. The example we create a bash script to display all database in MySQL or MariaDB:

#!/bin/bash

txtred=$(tput setaf 1)
txtgrn=$(tput setaf 2)
txtrst=$(tput sgr0)

echo "${txtred}Insert your password: ${txtrst}"
read password
echo
sleep 2
echo "${txtgrn}These are your database: ${txtrst}"
mysql -uroot -p$password -e"SHOW DATABASES;"

So the result will like this:

Another user may be will know database root password is qwerty. So, we must create the bash script to hide input from the user. There are two ways to hide input from the user. You can use option -s after command read so the script will become:

#!/bin/bash

txtred=$(tput setaf 1)
txtgrn=$(tput setaf 2)
txtrst=$(tput sgr0)

echo "${txtred}Insert your password: ${txtrst}"
read -s password
echo
sleep 2
echo "${txtgrn}These are your database: ${txtrst}"
mysql -uroot -p$password -e"SHOW DATABASES;"

And here is the result:

Or you can replace password with stars but we must change the script become like this:

#!/bin/bash

txtred=$(tput setaf 1)
txtgrn=$(tput setaf 2)
txtrst=$(tput sgr0)

echo "${txtred}Insert your password: ${txtrst}"
unset password;
while IFS= read -r -s -n1 pass; do
  if [[ -z $pass ]]; then
     echo
     break
  else
     echo -n '*'
     password+=$pass
  fi
done
echo
sleep 2
echo "${txtgrn}These are your database: ${txtrst}"
mysql -uroot -p$password -e"SHOW DATABASES;"

And here is the result:
hide input

Reference:
ryanstutorials.net
stackoverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *