HxHippy

read

Read a line from standard input

Overview

Reads a single line from standard input (or from a file descriptor specified with -u) and splits it into fields, assigning them to shell variables. Primarily used in shell scripts for user input.

Syntax

read [OPTIONS] [VARNAME1 VARNAME2 ...]

Common Options

-r

Raw mode. Do not allow backslashes to act as escape characters. Highly recommended.

-p PROMPT

Display PROMPT on standard error, without a trailing newline, before attempting to read input.

-s

Silent mode. If input is from a terminal, characters are not echoed. Useful for passwords.

-n NUMCHARS

Return after reading NUMCHARS characters rather than waiting for a newline.

-N NUMCHARS

Return after reading exactly NUMCHARS characters, ignoring delimiters, unless EOF or read error occurs.

-t TIMEOUT

Time out and return failure if a complete line of input is not read within TIMEOUT seconds.

-a ARRAYNAME

Assign the words read to sequential indices of the array variable ARRAYNAME, starting at zero.

-d DELIM

Continue until the first character of DELIM is read, rather than newline.

-u FD

Read input from file descriptor FD.

VARNAMEs

One or more shell variable names. If no VARNAMEs are given, the line read is stored in the `REPLY` variable.

Examples

$ read name

Reads a line from input and stores it in the variable `name`.

$ read -p "Enter your favorite color: " color

Prompts the user and stores their input in `color`.

$ read -s -p "Password: " secret_pass

Reads a password silently into `secret_pass`.

$ echo "apple banana cherry" | read fruit1 fruit2 fruit3

Pipes a string to `read`, assigning words to `fruit1`, `fruit2`, and `fruit3` (Note: in a subshell, variables may not persist as expected in all shells without workarounds).

$ read -r line < data.txt

Reads the first line from `data.txt` into `line` without interpreting backslashes.

$ while IFS= read -r record; do echo "Processing: $record"; done < employees.csv

Reads a file `employees.csv` line by line, preserving leading/trailing whitespace in each line.

$ read -n 1 -p "Proceed (y/n)? " answer

Reads a single character for a yes/no prompt.

$ read -t 5 -p "Quick, enter something: " value

Waits up to 5 seconds for input.

$ read -a words <<< "one two three four"

Reads words from a here-string into the array `words`. (`echo ${words[1]}` would output `two`).

readinputuser inputscriptingshell built-invariable assignment