Linux Know-How provides a collection of introductory texts on often needed Linux skills.

Using the read built-in command

The read built-in command is the counterpart of the echo and printf commands. The syntax of the read command is as follows:

read [options] NAME1 NAME2 ... NAMEN

One line is read from the standard input, or from the file descriptor supplied as an argument to the -u option. The first word of the line is assigned to the first name, NAME1, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name, NAMEN. If there are fewer words read from the input stream than there are names, the remaining names are assigned empty values.

The characters in the value of the IFS variable are used to split the input line into words or tokens; see Section 3.4.8. The backslash character may be used to remove any special meaning for the next character read and for line continuation.

If no names are supplied, the line read is assigned to the variable REPLY.

The return code of the read command is zero, unless an end-of-file character is encountered, if read times out or if an invalid file descriptor is supplied as the argument to the -u option.

The following options are supported by the Bash read built-in:

Table 8-2. Options to the read built-in

-a ANAMEThe words are assigned to sequential indexes of the array variable ANAME, starting at 0. All elements are removed from ANAME before the assignment. Other NAME arguments are ignored.
-d DELIMThe first character of DELIM is used to terminate the input line, rather than newline.
-ereadline is used to obtain the line.
-n NCHARSread returns after reading NCHARS characters rather than waiting for a complete line of input.
-p PROMPTDisplay PROMPT, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.
-rIf this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.
-sSilent mode. If input is coming from a terminal, characters are not echoed.
-t TIMEOUTCause read to time out and return failure if a complete line of input is not read within TIMEOUT seconds. This option has no effect if read is not reading input from the terminal or from a pipe.
-u FDRead input from file descriptor FD.

This is a straightforward example, improving on the script from the previous chapter:

michel ~/test> cat
# This script will test if you have given a leap year or not.

echo "Type the year that you want to check (4 digits), followed by [ENTER]:"

read year

if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 !=
"0") )); then
  echo "$year is a leap year."
  echo "This is not a leap year."

michel ~/test>
Type the year that you want to check (4 digits), followed by [ENTER]:
2000 is a leap year.

Last Update: 2010-12-16