Open In App

read command in Linux with Examples

Last Updated : 25 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

read command in the Linux system is used to read from a file descriptor. This command reads up the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero, this command may detect errors. But on success, it returns the number of bytes read. Zero indicates the end of the file. If some errors are found then it returns -1.

Let’s look deeper into its usage, syntax, options, and some common examples.

Syntax

read

The read command takes the user’s input and stores it into a variable that can be referenced later in the script.

Basic read Command Example

read commandread command

Options for the read Command

Options

Description

-p

Displays a prompt before reading input.

-t

Sets a timeout to wait for input.

-n

Limits the number of characters to read.

-s

Disables echoing the input (useful for password entry).

-d

Defines a delimiter other than a newline.

read Command Examples in Linux

read command without any option: The read command asks for the user’s input and exit once the user provides some input. Prompting for User Input

In the following example we are acquiring the user’s name and then showing the user’s name with a greeting.

echo "what is your name..?";read name;echo "hello $name"

Prompting for User Input

Conclusion

The read command’s ability to capture user input, read files, and handle input with various options makes it essential for interactive and automated scripts. By mastering this command and its various flags, you can make your shell scripts more dynamic and user-friendly.

read command in Linux – FAQs

What does the read command do in Linux?

The read command in Linux reads a line of input from the user or a file descriptor and stores it in a variable. It’s commonly used in shell scripts to capture user input or handle file operations.

How do I prompt the user for input in Linux using the read command?

You can use the -p option to display a prompt before reading the input.

read -p "Enter your name: " name

This will display a prompt asking for the user’s name and store the input in the name variable.

How do I limit the number of characters read can accept?

The -n option allows you to limit the number of characters the read command will accept.

read -n 5 name

This will only allow the user to enter up to 5 characters.

How do I set a timeout for the read command?

You can use the -t option to specify the number of seconds to wait for input before timing out.

read -t 10 name

This will wait for 10 seconds for the user to input their name before timing out.


Next Article

Similar Reads

three90RightbarBannerImg
  翻译: