Saturday, September 21, 2024
Google search engine
HomeGuest BlogsHow To Use The Bash read Command

How To Use The Bash read Command

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 CommandHow 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.

Option Description
-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.
-e Starts 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.
-r Disable backslashes to escape characters.
-s Does 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 outputread terminal output

The prompt waits for the user input.

3. Type a sentence and press Enter.

read command with sentence terminal outputread 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 terminalecho 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 outputread 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 outputread 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 terminalread 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 readpiping 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 outputread 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 outputread -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 outputifs 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 outputifs 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 outputread -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 outputread 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 outputread -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 outputread -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 outputread -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 terminalread 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 outputread -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

RELATED ARTICLES

Most Popular

Recent Comments