How to Use read Command in Linux

Spread the love

Sometimes while interacting with your Linux system you may need to prompt users for input or read input from files, or even want to set timeouts. You can perform these tasks and many others with the read command and its various options.

This article will teach you the basics of read command and its options using numerous code examples.

Content

What Is the Read Command

In Linux, you can use the read command to capture user input or read a line from standard input (stdin). This command reads the total number of bytes from the given file descriptor and stores them in the buffer. After that, it returns the number of bytes read, zero, or an error.

For example, if the number or count is zero, it refers to the end of the file. But on success, it returns the number of bytes read. If the read command finds some errors, it returns -1.

Before exploring the read command options, let’s first look at the syntax of the read command:

read [options] [name…]

Here, the options parameter specifies various flags that are used to modify the behavior of the read command. Furthermore, the name parameter specifies the name of multiple variables that are used to store the input. If no names are provided, the input is retained in the $REPLY bash variable.

Read Command Options

The Bash read command has many options to control user input. Some options don’t need extra parameters, while others do.

Let’s explore some options we can use with the read command:

Options Descriptions
-a <array> It stores the input as an array instead of separate variables.
-s Runs silently, meaning input is not displayed on the terminal
-e enables readline library support, allowing reading the input line
-i <prefix> provides an initial input value that appears at the prompt when using readline
-p <prompt> displays the specified prompt before reading the input
-u <file descriptor> reads from a specified file descriptor rather than the standard input (stdin)
-d <delimiter> allows you to specify an input line delimiter instead of the default newline character
-t <time> sets a timeout period for input; if the input is not received within this time, read returns a failure
-r when set, backslashes are not treated as escape characters
-n <number> reads only the specified number of characters

Type the following command to output the read command help menu:

head --help

How to Read Input Using Read Command

The most simple way to use the read command is to use it without any arguments or options. When you execute the read command alone, it will ask you to provide the input that you want to read. After providing input, it will exit and store it in its default variable named REPLY.

Let’s take this as an example:

read
<user_input>

Now, after providing input, let’s display it using the echo command:

echo $REPLY

While reading the input value, you can also store it in any other specific variables. For example, to store the result into a variable, type the read command followed by the variable name:

read variable1
<user_input>

Now, to display the result, you need to use the echo command with the variable that stores your value:

echo $variable1

Reading Multiple Values

There is no direct way to read multiple values using the read command. However, you can split the single input sentence into multiple words and store them in different variables.

Let’s consider the following example:

read variable1 variable2 variable3
<user_input>

Here, you store the first word of the sentence in the first variable, and the second word in the second variable, and all the remaining words in the last provided variable.

Let’s return the output using the following command:

echo <$variabl_namee>

Reading From a File

While read is primarily for user input, you can also use it to read lines from a file. To do this, simply use the while loop, echo command, and read command followed by a specific variable name:

while read line; do
echo "$line"
done < samplefile.txt

Here, the while loop reads each line of the “samplefile.txt” and records it in the variable line. After reading all the lines of a file, the echo command shows the value of the line.

Reading Input in a Loop

You can also capture user input in a repeated sequence by using a read with a while loop. This is useful when you want to collect multiple inputs or continue until a specific condition is met.

For example, let’s read multiple inputs and also display them on the terminal:

while read line; do
echo "Line: $line"
done

Moreover, the loop continues until it receives an end-of-file (EOF) signal, usually by pressing Ctrl + D.

How to Prompt Input Using Read Command

You can also create interactive prompts that will display before the user input. You can accomplish this by using the -p option along with the read command.

Let’s display a custom prompt and also capture the input:

read -p "Enter your Name: " name

Limiting User Input While Reading

Want to control what users can enter? Use the -n option with read to specify your desired character length. For example, if you want to capture the first 4 characters of the user input, use the below command:

read -n 9 variable

After executing the above command, it allows you to enter only nine characters. Limiting user input while reading will eliminate the need for a delimiter and also doesn’t split the input into words.

Separating Output Fields Using IFS

You can use the Internal Field Separator (IFS) variable with the read command to determine how to split the input into separate fields. By default, IFS uses whitespace characters (tab, newline, and space) as field separators. However, you can customize the IFS to suit your needs.

For example, you can specify the colon (:) value as a delimiter:

IFS=':' read name password
<user_input>
echo "Name: $name, Password: $password"

With the IFS variable, you can capture multiple line inputs from the user and separate them based on the separator value.

Setting Timeout on Read

You can also configure a timeout for the read command using the -t option. This is useful if you want to make sure the script doesn’t rely on user input for a long time.

Let’s set a 10-second timeout using the -t option:

read -t 10 -p "Enter your name (10 seconds timeout): " name 
<user_input>
echo "Hello, $name!"

If the user doesn’t type anything within 10 seconds, the script continues execution.

How to Hide User Input

Sometimes, you may want to hide the user’s input, such as when entering sensitive information like passwords. You can achieve this using the -s option of the read command:

read -s -p "Enter your password: " password
<user_input>

After storing the password in the specified variable, you can display it in the terminal using the echo command:

echo -e "\nPassword: $password"

Here, the -e flag allows the interpretation of escape sequences, and \n escape sequence adds a new line before the output.

Wrapping Up

By the time you finish reading this article and working through the examples, you’ll be familiar with using the read command in the Linux terminal. However, there are several more commands to explore. Continue reading to find out the basic commands for newcomers.

Image credit: Gabriel Heinzer via Unsplash. All screenshots by Haroon Javed.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.
By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time. Subscribe


Haroon Javed
Contributor

Haroon is a lifelong tech enthusiast with over five years of experience writing thousands of articles about Linux, programming languages, and more. He loves exploring new technologies and experimenting with them to find innovative ways to use them. Haroon’s work has been featured on various online platforms, including HTG, Baeldung, and LinuxHint.

Comments (2)