read Command
The read command is a built-in shell command in Linux and Unix-like operating systems used to read a single line from standard input (or a specified file descriptor) and split it into fields, assigning them to shell variables. It is essential for creating interactive shell scripts.
Syntax
Description
When read is executed, it waits for input from the user (or a pipe/file). Once a newline character is encountered, the input is read. By default, the input is split into words based on the characters in the IFS (Internal Field Separator) variable, and these words are assigned to the provided VARNAMEs. If fewer variable names are provided than words, the remaining words are assigned to the last variable. If more variable names are provided, the extra variables are set to empty.
Common uses include:
- Prompting users for input in shell scripts.
- Reading data from files line by line.
- Parsing structured data from input streams.
- Implementing simple interactive command-line applications.
Common Options
| Option | Description |
|---|---|
-p PROMPT |
Display PROMPT on standard error, without a trailing newline, before attempting to read any input. |
-r |
Raw input. Backslash does not act as an escape character. Useful when reading lines that might contain backslashes. |
-t TIMEOUT |
Timeout. Cause read to exit after TIMEOUT seconds if input is not available. |
-n NCHARS |
Read NCHARS characters rather than up to a newline. |
-s |
Silent mode. Do not echo input coming from a terminal. Useful for reading passwords. |
-a ARRAY |
Read words into sequential elements of ARRAY, starting at index 0. |
Examples
Read user's name
Prompts the user to enter their name and stores it in the name variable.
Read multiple variables
Reads two words from input and assigns them to first_name and last_name.
Read a password silently
Prompts for a password without echoing the input to the screen.
Read a line from a file
Reads input.txt line by line, processing each line within the loop. IFS= prevents leading/trailing whitespace trimming, and -r prevents backslash interpretation.
Read with a timeout
Waits for 5 seconds for user input. If no input is provided, it exits.