How To Use The Bash read Command

February 21, 2022

Introduction

The Bash read command is a built-in utility that reads text from standard input. The tool offers many functionalities for reading user input, helping make Bash scripts interactive.

This guide explains how the Bash read command works through various examples and use cases.

How to Use the Bash read Command

Prerequisites

Bash read Syntax

The syntax for the Bash read command is:

read <options> <arguments>

The read command takes the user input and splits the string into fields, assigning each new word to an argument. If there are fewer variables than words, read stores the remaining terms into the final variable.

Specifying the argument names is optional. The command stores a user's input into the $REPLY variable by default.

Bash read Options

The Bash read command comes with many options to control the user input. Some options do not require additional parameters, while others have mandatory parameters.

The table below shows all the possible command options and their description.

OptionDescription
-a <array>Assigns the provided word sequence to a variable named <array>.
-d <delimiter>Reads a line until the provided <delimiter> instead of a new line.
-eStarts an interactive shell session to obtain the line to read.
-i <prefix>Adds initial text before reading a line as a prefix.
-n <number>Returns after reading the specified number of characters while honoring the delimiter to terminate early.
-N <number>Returns after reading the specified number of chars, ignoring the delimiter.
-p <prompt>Outputs the prompt string before reading user input.
-rDisable backslashes to escape characters.
-sDoes not echo the user's input.
-t <time>The command times out after the specified time in seconds.
-u <file descriptor>Read from file descriptor instead of standard input.

Continue reading to see how the read command works through various examples.

Bash read Examples

The read command functions without any arguments or options. To test the command, follow the steps below:

1. Open the terminal.

2. Write the command and press Enter:

read
read terminal output

The prompt waits for the user input.

3. Type a sentence and press Enter.

read command with sentence terminal output

The terminal returns to its normal state.

4. Retrieve the message with the echo command:

echo $REPLY
echo reply variable terminal

The $REPLY variable stores the read command message.

Below are examples demonstrating more complex use cases for the Bash read command.

Arguments

Save the user input into a specified variable by providing an argument:

read input

Retrieve the message with:

echo $input
read into variable and echo terminal output

Alternatively, split the user input into different variables by adding multiple arguments.

For example:

read var1 var2

The user input splits into individual words. Retrieve them with:

echo $var1
echo $var2
read into two variables and echo terminal output

When the user input has more words than there are variables, the extra words are assigned to the last provided variable:

read var1 var2
foo bar baz
echo $var1
echo $var2
read variables and word count terminal

If there are fewer words than variables, the remaining variables are empty.

Piping

Piping takes the standard output from one command and parses it as standard input for another process. Use echo and pipe the information to read for immediate parsing. For example:

echo "Hello world!" | (read var1 var2; echo $var1; echo $var2)
piping echo and read

The parentheses create a subshell with multiple commands, and the individual variables print to the console.

Heredoc

Another way to input text into the read command is using heredoc notation. For example:

read var1 var2 <<< "Hello world!"
echo $var1
echo $var2
read heredoc terminal output

The read command expects an input stream literal, and the redirection identifier (<<<) inputs the herestring.

Delimiters

The read command defines two delimiter types:

1. The delimiter for the read command.

By default, pressing Enter (newline) ends the command. Add the -d tag and provide a different delimiter in quotes to terminate differently.

For example:

read -d "-"
read -d terminal output

Instead of a new line, the new delimiter is a dash (-) instead of a new line. The command terminates when reaching the delimiter, disregarding the number of arguments. The response in $REPLY or the provided variable stores the user input without the dash (-).

2. The delimiter for splitting fields.

The variable $IFS (Internal Field Separator) stores the word delimiters. The default value by which words split is a space " ". Set the $IFS variable to a different value to control this behavior.

For example, to separate words by dashes, use:

IFS="-"
echo "Hello-world!" | (read var1 var2; echo $var1; echo $var2)
ifs separator terminal output

Add different separators to split fields by different values:

IFS="-_"
echo "Hello_world-!" | (read var1 var2 var3; echo $var1; echo $var2; echo $var3)
ifs multiple separators terminal output

The separator is one character long, and $IFS takes each stated divider individually.

Note: Learn also how to use the read command and while loop to read files line by line in Bash.

Prompt

Use the read command to create interactive prompts. Add the -p tag and provide the prompt text, for example:

read -p "Enter your username: " username

The prompt text prints and requires user input. The text saves to the variable $username.

echo Your username is $username.
read -p prompt terminal output

Use the -p option in Bash scripts to work with prompt creation.

Hide User Input

The read command offers the -s tag to hide sensitive information input. A common use case is to combine -s with the -p tag to create a password prompt.

For example:

read -p "Enter your password: "$'\n' -s password

The user's input is invisible. However, echoing the message displays the password:

echo $password
read password prompt terminal output

Be wary of this behavior when using read in scripts that prompt for passwords.

Note: Use unset <variable name> to remove the user input.

Set Character Limit

The read command offers two options when limiting the number of characters for the user input:

1. Use the -n option and provide a number to set the character limit. For example:

read -n 3
read -n 3 terminal output

Press Enter after one character to end the command before reaching the character limit. Without pressing Enter, the command exits automatically after three characters.

2. Use the -N option and provide a number to set the character limit while ignoring the delimiter. For example:

read -N 3
read -n 3 no delimiter terminal output

Pressing Enter does not end the command. However, the keystroke counts as a character.

Set Timeout

Set a timeout on read to limit the time taken to input text:

read -t 5

The command automatically ends after the provided time limit.

Arrays

Instead of using individual variables to store a string, add the -a option to save the input in an array. For example:

read -a array <<< "Hello world!"

Retrieve the array elements with:

echo ${array[0]}
echo ${array[1]}
read -a array terminal output

Alternatively, use a for loop to iterate through the array.

Escape Characters and Backslashes

The read command allows splitting long inputs into multiple lines using backslashes. For example:

read password prompt terminal output
Hello \
world\
!
read backslash behavior terminal

Pressing Enter after the backslash does not end the command and expects further input on the following line.

To ignore backslash interpretation, add the -r option:

read -r <<< "Hello\world!"; echo $REPLY
read -r terminal output

Use this option when parsing file paths and any text where the backslash has meaning.

Note: Refer to our guide on running Bash scripts to learn how to run a Bash script using various methods.

Conclusion

After reading this article and working through the examples, you now know how to utilize the read command in the Linux terminal.

Knowing how to use the utility helps make Bash scripts interactive by catching user inputs.

Master Bash with our ultimate Bash commands guide, which also contains a downloadable cheat sheet.

Was this article helpful?
YesNo
Milica Dancuk
Milica Dancuk is a technical writer at phoenixNAP with a passion for programming. With a background in Electrical Engineering and Computing, coupled with her teaching experience, she excels at simplifying complex technical concepts in her writing.
Next you should read
How to Use the Bash let Command {with Examples}
January 20, 2022

The Bash let command is a built-in utility used for evaluating arithmetic expressions. Learn how to use the Bash let command in this tutorial.
Read more
Bash Export Variable
December 30, 2021

All the variables the user defines inside a shell are local by default. It means that child processes of the shell do not inherit the values of the shell's variables. To make them available to child processes...
Read more
Bash wait Command with Examples
September 23, 2021

The wait command helps control the execution of background processes. Learn how to use the wait command through hands-on...
Read more
How To Check If File or Directory Exists in Bash
November 29, 2023

Searching for specific files or directories can be time-consuming. You can use a bash command or script to streamline the process. This...
Read more