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

read [OPTION]... [VARNAME]...

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

read -p "Enter your name: " name echo "Hello, $name!"

Prompts the user to enter their name and stores it in the name variable.

Read multiple variables

read -p "Enter first name and last name: " first_name last_name echo "First Name: $first_name, Last Name: $last_name"

Reads two words from input and assigns them to first_name and last_name.

Read a password silently

read -s -p "Enter your password: " password echo "\nPassword entered: $password"

Prompts for a password without echoing the input to the screen.

Read a line from a file

while IFS= read -r line do echo "Processing: $line" done < input.txt

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

read -t 5 -p "You have 5 seconds to respond: " response if [ -z "$response" ]; then echo "Time's up!" else echo "You responded: $response" fi

Waits for 5 seconds for user input. If no input is provided, it exits.

See also