Situatie
We can simply get user input from the read command in BASH. It provides a lot of options and arguments along with it for more flexible usage, but we’ll cover them in the next few sections.
Solutie
Pasi de urmat
#!usr/bin/env bash read name echo "Hello, $name"
So, in the above script, the “#!/usr/bin/env bash” is the shebang operator that indicates the interpreter to run the script in the BASH environment. We have used the read command to get the user input in the variable name. The echo command is an optional command to just verify that we have stored the input in the name variable. We use $ in front of the variable command so as to fetch and parse the literal value of the variable.
Prompt String
Using this argument, we can prompt a string before the input. This allows the user to get the idea of what to input without using echo before the read command. Let us take a look at the demonstration of the argument of prompting a string to the read command.
#!usr/bin/env bash read -p "Enter your name : " name echo "Hello, $name"
Password Input
Now assume that we want to type in the password in the input and how insecure it would be to display while the user is typing. Well, we have the solution for that. We can use the -s argument to silent the echo from the user input. This allows working with the read command in a secure way.
#!usr/bin/env bash read -sp "Enter your password : " pswd echo -e "\nYour password is $pswd"
In the above demonstration, the input is silenced i.e. the interface doesn’t print what the user is typing. But we can see that I typed 12345 and is stored and retrieved later from the variable. You can notice that we have nested the arguments -s and -p as -sp to use both the arguments together. Also, the echo command is modified as we use the -eargument to use formatted strings i.e use “\n” and other special characters in the string.
Leave A Comment?