Skip to content

read

Using the built-in read command 

read [options] [variable_name... ]

NOTE: If no variable name is specified, the input goes into the default variable named REPLY (accessible via $REPLY). 

NOTE: If more than one variable name is specified, the first word (the input up to the first space or tab) is assigned to the first variable, the second word assigned to the second variable, and so on, with any leftover words assigned to the last variable.

For help, use: help read 

Option What It Does
-r Do not strip backslashes from input
-p Display a prompt. e.g.  
read –p "Enter a number: " name
-s (Silent/Secret) Do not echo what was entered by user. Useful for password entry.
-a Store the input in an array (identified by variable_name)
-n
-N
Limit the number of input characters to n characters or less.
e.g.  read –n 5 –p "Enter up to 5 characters: " characters 

read will stop collecting input after the specified number of characters or after enter  is hit. 

If exactly 5 characters were required, use –N instead of –n.
-t Specify a timeout (in seconds) for the read command to wait for input. 

E.g. 
read -t 3 word ; if [ -z $word ]; then echo "Input timed out"; else echo "You entered $word"; fi

Acting on Lines in a File

From the Command Line

The following example shows reading one line at a time from a text file input.txt and performing some action with each line:

while read line ; do echo $line ; done < input.txt

From a Script

script.sh

while read line
do
  echo $line
done < /dev/stdin

The script can process the lines in the input file input.txt with the following command:

cat input.txt | script.sh