Read (Unix)

Last updated
read
Operating system Unix, Unix-like, Inferno
Type Command

read is a command found on Unix and Unix-like operating systems such as Linux. It reads a line of input from standard input or a file passed as an argument to its -u flag, and assigns it to one or more variables. Each variable is assigned a successive token (word) from the input where tokens are normally split either by spaces or tabs. If there are more variables than tokens then the remaining variables are unchanged. If there are more tokens than variable then the remaining tokens are assigned to the last variable listed in the command. [1] If the -a flag is used all of the tokens are loaded as separate items into the 1st argument as an array. It is built into shells such as Bash. [2]

Contents

Configuration

The command supports several options via flags. It can be configured to issue a message using -p instead of needing to use the echo command. It can also superficially hide text using the -s flag, limit the amount of characters with -n, store the result in an array with -a, and timeout after a certain amount of time with -t. The -e flag tells read to use the GNU readline library to handle the input. The -i arguments flag, which can only be used with -e, supplies a default input string which the user can then accept or modify. [3]

Usage

The read command is used to take input from the user in shell scripts. It will use the variable $REPLY variable for storing replies when no variable is specified. [3]

Consider the following examples using the input string "The rain in Spain"

      read             #The entire input is assigned to $REPLY          read word1 rest  #word1 is assigned "The and rest is assigned rain in Spain.       read a b c d e   #a<-"The", b<-"rain", c<-"in", d<-"Spain", e is unchanged.       read -p "Enter a list of words" a b #each word is a separate entry in a.  b is unchanged.

References

  1. Dancuk, Milica (Feb 21, 2022). "How To Use The Bash read Command". phoenixnap.com. phoenixNAP Global IT Services. Retrieved Mar 31, 2025.
  2. "Guide to the Linux read Command". Baeldung. 2023-06-08. Retrieved 2025-03-31.
  3. 1 2 Murray, Christopher (2019-10-19). "Linux Read Command: 6 Practical Examples". linuxhandbook.com. Retrieved 2024-02-17.