Prompt for input in bash

How to Prompt for Input in Bash

Wondering how to prompt for input in Bash? 

Then you’ve come to the right place! 

This comprehensive guide will walk you through the various methods to obtain user input in your scripts. When writing scripts in Bash, we often need to prompt for input from the users. In this case, it’s hard to know what type of input is required. 

Whether you’re a beginner or an experienced Bash user, understanding these techniques will help you save time and avoid headaches while scripting.

In this guide, we will show you two methods to do this, explaining each method in detail. 

Let’s get started!

How to Prompt for Input in Bash: 2 Methods

Method 1: Use the read Command to Prompt for Input in Bash

The read command is widely used to prompt input in the Bash script. It is a counterpart of the echo and printf commands. In other words, we can use the read command to prompt for input similar to echo and printf.

The syntax for the read command is as shown below:

read [options] NAME1 NAME2 ... NAMEN

There are different ways to take input from the read command. In this section, we’ll discuss three ways: 1) user variable input, 2) password input, and 3) system variable input.

For the purposes of this guide, we’ll create a Bash script. 

First, open the terminal by pressing the CTRL + ALT + T keys. After that, create a new script file by using the nano editor or vim editor as shown below:

nano test.sh

After that, enter the following code, which will be inserted into our test.sh Bash script file:

#!/bin/bash
# read command examples

Now that we have the sample file ready, we’ll write the code for the read command in the same file in the upcoming sections.

1. Prompt for Input in the Assigned Variable

One of the useful features of the read command is its ability to prompt the user for input and assign it to a variable. Using the -p option, you can display a prompt explaining the type of data expected from the user.

Let’s try an example. 

To take the year as an input, you’ll type the following:

#!/bin/bash
# read command example
# This script will test if you have given a leap year or not.
read -p "Type the year that you want to check (4 digits), followed by [ENTER]:" year
if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 !=
"0") )); then
  echo "$year is a leap year."
else
  echo "This is not a leap year."
fi

Press CTRL + S keys to save the script and CTRL + X keys to exit the nano editor. 

Lastly, execute the script using the command below:

bash test.sh

You should get an output as shown in the screenshot below:

prompt for input in bash 1

We’ve prompted the user to input values using the read command. In the next section, we’ll look into how you can prompt for a silent input using the read command.

2. Prompt for the Silent Input

Sometimes, we have to take input from the user but don’t want it to appear on the screen. 

One such scenario is taking the user’s password. Here, we’ll use the -s option along with the read command. 

Let’s try an example to learn how to prompt for input in Bash!

To take the user’s username and password and validate the password by creating a shell function, we’ll type the following:

#!/bin/bash
# Function to validate password complexity
validate_password() {
    local password=$1
    # Perform your custom password validation here
    # For example, check for minimum length, uppercase, lowercase, and special characters
    if [[ ${#password} -lt 8 || !($password =~ [[:upper:]]) || !($password =~ [[:lower:]]) || !($password =~ [[:digit:]]) || !($password =~ [[:punct:]]) ]]; then
        echo "Password must be at least 8 characters long and contain uppercase, lowercase, digit, and special characters."
        return 1
    fi
    return 0
}
# Prompt for username and password
read -p "Username: " username
while true; do
    read -s -p "Password: " password
    echo
    validate_password "$password" && break
done
# Perform some action with the input
echo "Logging in..."
# Your login logic here
echo "Welcome, $username!"
echo “Your password is $password!”

Now, save the script by pressing CTRL + S. To execute the script, type:

bash test.sh

Once you execute it, the input prompt will take the value but it won’t appear on the terminal unless you print it using the echo command.

Here, we’ve used the variables to prompt for input in Bash from the user. In addition, we can take input without defining any user-defined variables which we will show in the next section.

3. Prompt for the Unassigned Input

When you use a user-defined variable with a read command, the input from the terminal is saved in that variable. However, if you don’t use any variable, then the input is saved in the $REPLY by default.

To demonstrate how to prompt for input in Bash in unassigned variable, we’ll modify our script as shown below:

#!/bin/bash
# Prompt for input with a menu
echo "Welcome to the script!"
while true; do
    echo "Please select an option:"
    echo "1. Start"
    echo "2. Stop"
    echo "3. Quit"
    read -p "Enter your choice: " -r
    # Process user input
    case $REPLY in
        1)
            echo "Starting..."
            # Start logic here
            ;;
        2)
            echo "Stopping..."
            # Stop logic here
            ;;
        3)
            echo "Quitting..."
            exit 0
            ;;
        *)
            echo "Invalid choice. Please try again."
            ;;
    esac
    echo
done

Note: We’ve used -r with the read command. This option processes the raw input. To elaborate, the read command treats the input as raw and does not interpret backslashes as escape characters. If we want to prevent the interpretation of backslashes as the input, we use the -r option with the read command. 

We’ve used case statement to check the user’s input. You can use if else block as well.

You should get an output as shown in the screenshot below:

prompt for silent input

So far, we’ve prompt for input in Bash using a single variable. However, we can achieve the same with multiple variables which we’ll cover in the next section.

4. (Optional) Prompt for Multiple Inputs in Bash

By using the read command, we can also take multiple inputs. Multiple inputs enable users to simplify the code and prevent the script from having redundant commands. 

For instance, you want the user to input three values. Instead of using the read command thrice, you’ll use it once and mention the variable names after the prompt. This is particularly useful when we want to take a similar type of input.

Here is the sample code:

#!/bin/bash
# Example to demonstrate multiple inputs using the read command
# Prompt for multiple inputs using a single read command
read -p "Enter your name, age, and email (separated by spaces): " name age email
# Display the collected information
echo "Name: $name"
echo "Age: $age"
echo "Email: $email"

In this example, we’ve used space as a delimiter. If we want to change the delimiter for the input, we’ll set the IFS to the comma and then we use the <<< redirection to assign the values to the variables name, age, and email:

IFS=',' read -r name age email <<< "$name"

The output is as shown in the screenshot below: 

prompt for input in bash using read

Note: This method will only work if you want to take a similar input using the read command. To elaborate further, you can’t take a normal input and a silent input using the same read command. Since the options you add with the read command apply to all the variables, ensure that the appropriate read flags are used.

5. (Optional) Prompt for a Yes/No Input Using read

We can also use the read command as a prompt for a yes or no question. For this type of script, we’ll use the case block to evaluate whether the user has entered y or n

Here is the code for this script:

while true; do
    read -p "Do you wish to install this program? " yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

Method 2: Use the select Command

The second method to prompt for input is the select command. 

The select command is specifically useful when we want to check the user’s input from a range of selections. This command displays the available choices, and the user types a number corresponding to the choice. 

Here is a sample script:

#!/bin/bash
echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) make install; break;;
        No ) exit;;
    esac
done

By running the below script, assuming we use the same test.sh file as Method 1, we should get an output as shown in the screenshot below:

prompt for input in bash using select

In this script, we’ve used the select command to check users’ input in the range [yes, no]. Then, we used the case statement to execute the rest of the code.

With select, we don’t need a loop, as it loops automatically over the range of choices.

Conclusion

This concludes our comprehensive tutorial on how to prompt for input in Bash.

Throughout this guide, you have gained valuable knowledge on two input commands: read and select. Furthermore, you have also learned how to use the read command using several options such as -s, -p, and -r.

Become an expert at Bash arguments by learning how to pass a named argument and check number of arguments in Bash

If this article helped you, please share it

Related Posts