How to Read User Input in Bash

Reading user input in Bash is a common task that allows scripts to interact with users. The primary command used for this purpose is read. This command reads a line of input from the user and assigns it to a variable. Below, we will explore how to use the read command effectively.

Basic Syntax of the read Command

The basic syntax for the read command is as follows:

read variable_name

In this syntax, variable_name is the name of the variable that will store the user input.

Example of Reading User Input

Here’s a simple example of how to read user input in a Bash script:

#!/bin/bash
# Prompt the user for their name
echo "Please enter your name:"
read user_name
echo "Hello, $user_name!"

In this example:

  • The script prompts the user to enter their name.
  • The read user_name command waits for the user to input their name and stores it in the variable user_name.
  • The script then greets the user using the value stored in user_name.

Reading Multiple Inputs

You can also read multiple inputs in a single line by specifying multiple variable names:

#!/bin/bash
# Prompt the user for their first and last name
echo "Please enter your first and last name:"
read first_name last_name
echo "Hello, $first_name $last_name!"

In this example:

  • The user is prompted to enter their first and last name in a single line.
  • The read command assigns the first input to first_name and the second input to last_name.
  • The script then greets the user using both names.

Using Prompts with read

You can also provide a prompt directly within the read command using the -p option:

#!/bin/bash
# Prompt the user for their age
read -p "Please enter your age: " age
echo "You are $age years old."

In this example:

  • The -p option allows you to specify a prompt message directly in the read command.
  • The user’s input is stored in the variable age, which is then used in the output message.

Reading Input Without Echoing

If you want to read sensitive information, such as a password, without displaying it on the screen, you can use the -s option:

#!/bin/bash
# Prompt the user for a password
read -sp "Please enter your password: " password
echo
echo "Password entered."

In this example:

  • The -s option suppresses the output, so the password is not displayed as the user types it.
  • The script then confirms that the password has been entered.

Conclusion

Reading user input in Bash is a straightforward process that enhances the interactivity of your scripts. By using the read command, you can easily capture user input and utilize it within your scripts. Whether you need to read a single value, multiple values, or sensitive information, the read command provides various options to suit your needs. Understanding how to effectively use this command will allow you to create more dynamic and user-friendly Bash scripts.