How to Prompt Bash for User Input
Prompting Bash for user input is easy. You can do it through the “read” command. Let’s divide this section further to discuss some examples:
1. The Basic Approach
First, you must create a Bash script and give it the executable permissions. Here, we use the “touch” command to create a “.sh” file. Then, use chmod to give the executable permission.
chmod u+x input.sh
nano input.sh
Now, let’s create a script which takes two numbers from the user and perform the addition.
echo "Provide A Number"
read num1
echo "Provide An Another Number"
read num2
sum=$((num1 + num2)
echo "The Sum of $num1 and $um2 is $sum"
Here, we prompt the user to get the “num1” and “num2” numbers to process them in the sum variable to print their sum. Finally, run the script, and the system will ask you to enter two numbers.
2. The Advanced Approach
Let’s look at the advanced application of the “read” command and create a script that decides the output based on the user input.
echo "Enter your Name"
read name
echo "Enter your Designation:"
echo "1. Manager"
echo "2. Developer"
echo "3. Content Writer"
read designation
case $designation in
"Manager")
department="Management Department on the 3rd Floor"
;;
"Developer")
department="Development Department on the Ground Floor"
;;
"Content Writer")
department="Content Department on the 2nd Floor"
;;
*)
departement="Unknown entry please contact with HR"
;;
esac
echo "Name: $name"
echo "Designation: $designation"
echo "Department: $department"
Once you run the script, enter your name and designation, and it produces the following output:
On the contrary, if you enter any designation other than the given options, the result would be:
Conclusion
Writing the Bash scripts can be confusing sometimes. Users often search for the method to create a prompt in Bash to get the user input. Considering this, we explained the same in this guide. Furthermore, we also used the examples of using the “read” command in basic and advanced scripts so that you can implement it without any further queries.