How to take password interactively in a Bash shell script
In Category Bash
If you are not familiar with interactive bash programming, please read this article as well. Typically “read” command is used to prompt the user to respond and read the input from standard input. The “read” command, by default, shows whatever is typed by the user on the terminal. But for reading a password on terminal requires character echo to be turned off. The “read” command provides an option “-s” to read the input in silent mode. Please note that “read” is an in-built command provided by Bash shell.
The following example script shows how to implement it.
#!/bin/bash PASS="cool" read -s -p "Password: " ans echo if [ "$PASS" == "$ans" ]; then echo "Welcome, Neo" else echo "Wrong password. Do I know you?" fi
The following shows what happens when the above script is run:
[neo@dot ain]$ sh password.sh Password: <-- typed "cool" here Welcome, Neo [neo@dot ain]$ sh password.sh Password: <-- typed "hot" here Wrong password. Do I know you? [neo@dot ain]$
In the above script, “-s” option tells “read” command to read the input in silent mode, “-p” option tells the prompt string and the last arguement “ans” is the name of the variable to which the user input should be set to. Once the read command is finished, the variable “$ans” will contain whatever typed by the user.
Recent Comments