BASH Programming

How to Prompt Bash for User Input

Bash lets you write and build the detailed programs like every other programming language. The Bash scripting helps the developers to make outstanding programs as it is also an easy-to-learn but powerful language like Python and C++. However, many Bash beginners do not know the correct ways to write the scripts which can take the custom inputs. So, in this guide, we will discuss how you can prompt Bash to take the user input with the help of examples.

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.

touch input.sh
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.

#!/bin/bash
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.

./input.sh

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.

#!/bin/bash
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.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.