This is an old revision of the document!

The read builtin command

read something about read here!

read [-ers] [-u fd] [-t timeout] [-p <PROMPT>] [-a <ARRAY>] [-n <NCHARS>] [-d <DELIM>] [-i <TEXT>] [<NAME...>]

The read builtin reads one line of data (text, user input, …) from standard input or a supplied filedescriptor number into one or more variables named by <NAME…>.

If <NAME…> is given, the line is word-split using IFS variable, and every word is assigned to one <NAME>. The remaining words are all assigned to the last <NAME> if more words than variable names are present.

If no <NAME> is given, the whole line read (without performing word-splitting!) is assigned to the shell variable REPLY. Then, REPLY really contains the line as it was read, without mangeling pre- and postfix spaces and other things!

while read -r; do
done < text.txt

-a <ARRAY>read the data word-wise into the specified array <ARRAY> instead of normal variables
-d <DELIM>recognize <DELIM> as data-end, rather than <newline>
-eon interactive shells: use Bash's readline interface to read the data
-i <STRING>:V4: preloads the input buffer with text from <STRING>, only works when Readline (-e) is used
-n <NCHARS>reads <NCHARS> characters of input, then quits
-N <NCHARS>:V4: reads <NCHARS> characters of input, ignoring any delimiter, then quits
-p <PROMPT>the prompt string <PROMPT> is output (without a trailing automatic newline) before the read is performed
-rraw input - disables interpretion of backslash escapes and line-continuation in the read data
-ssecure input - don't echo input if on a terminal (passwords!)
-t <TIMEOUT>wait for data <TIMEOUT> seconds, then quit (exit code 1). :V4: Fractional seconds ("5.33") are allowed. A value of 0 immediately returns and indicates if data is waiting in the exit code. Timeout is indicated by an exit code greater than 128. If timeout arrives before data is read completely (before end-of-line), the partial data is saved.
-u <FD>use the filedescriptor number <FD> rather than stdin (0)

When both, -a <ARRAY> and a variable name <NAME> is given, then the array is set, but not the variable.

Of course it's valid to set individual array elements without using -a:

read MYARRAY[5]

Reading into array elements using the syntax above may cause pathname expansion to occur.

Example: You are in a directory with a file named x1, and you want to read into an array x, index 1 with

read x[1]
then pathname expansion will expand to the filename x1 and break your processing!

Even worse, if nullglob is set, your array/index will disappear.

To avoid this, either disable pathname expansion or quote the array name and index:

read "x[1]"

Status Reason
0 no error
0 error when assigning to a read-only variable FIXME is this intended?
2 invalid option
!=0 invalid filedescriptor supplied to -u
!=0 end-of-file reached
!=0 timeout (see -t)

A rudimentary replacement for the cat command: read lines of input from a file and print them on the terminal.

opossum() {
  while read -r; do
    printf "%s\n" "$REPLY"
  done <"$1"

Note: Here, read -r and the default REPLY is used, because we want to have the real literal line, without any mangeling. printf is used, because (depending on settings), echo may interpret some baskslash-escapes or switches (like -n).

Remember the MSDOS pause command? Here's something similar:

pause() {
  local dummy
  read -s -r -p "Press any key to continue..." -n 1 dummy


  • -s to suppress terminal echo (printing)
  • -r to not interpret special characters (like waiting for a second character if somebody presses the backslash)

Simple Split

Read can be used to split a string:

var="one two three"
read -r col1 col2 col3 <<< "$var"
printf "col1: %s col2: %s col3 %s\n" "$col1" "$col2" "$col3"

Take care that you cannot use a pipe:

echo "$var" | read col1 col2 col3 # does not work!
printf "col1: %s col2: %s col3 %s\n" "$col1" "$col2" "$col3"
Why? because the commands of the pipe run in subshells that cannot modify the parent shell. As a result, the variables col1, col2 and col3 of the parent shell are not modified (see article: Bash and the process tree).

If the variable has more fields than there are variables, the last variable get the remaining of the line:

read col1 col2 col3 <<< "one two three four"
printf "%s\n" "$col3" #prints three four

Changing The Separator

By default reads separates the line in fields using spaces or tabs. You can modify this using the special variable IFS, the Internal Field Separator.

IFS=":" read -r col1 col2 <<< "hello:world"
printf "col1: %s col2: %s\n" "$col1" "$col2"
Here we use the var=value command syntax to set the environment of read temporarily. We could have set IFS normally, but then we would have to take care to save its value and restore it afterward (OLD=$IFS IFS=":"; read ….;IFS=$OLD).

The default IFS is special in that 2 fields can be separated by one or more spaces. When you set IFS to something else, the fields are separated by exactly one character:

IFS=":" read -r col1 col2 col3 <<< "hello::world"
printf "col1: %s col2: %s col3 %s\n" "$col1" "$col2" "$col3"
See how the :: in the middle infact defines an additional empty field.

The fields are separated by exactly one character, but the character can be different between each field:

IFS=":|@" read -r col1 col2 col3 col4 <<< "hello:world|in@bash"
printf "col1: %s col2: %s col3 %s col4 %s\n" "$col1" "$col2" "$col3" "$col4"

asksure() {
echo -n "Are you sure (Y/N)? "
while read -r -n 1 -s answer; do
  if [[ $answer = [YyNn] ]]; then
    [[ $answer = [Yy] ]] && retval=0
    [[ $answer = [Nn] ]] && retval=1

echo # just a final linefeed, optics...

return $retval

### using it
if asksure; then
  echo "Okay, performing rm -rf / then, master...."
  echo "Pfff..."

Note: :V4: The -i option was introduced with Bash 4

read -e -p "Enter the path to the file: " -i "/usr/local/etc/" FILEPATH

The user will be prompted, he can just accept the default, or edit it.

  • POSIX® only specified the -r option (raw read); -r is not only POSIX, you can find it in earlier Bourne source code
  • POSIX® doesn't support arrays
  • REPLY is not POSIX®, you need to set IFS to the empty string to get the whole line for shells that don't know REPLY.
    while IFS= read -r line; do
    done < text.txt
This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
Dan Douglas, 2011/09/13 06:07

There's something slightly fishy going on with how the read arguments are parsed. In reality it's arbitrary expansions.

$ x='['; y=']'; z='+++'; while read -r "a${x}v${z%+}$y"; do :; done < <(printf '%s\n' {a..d}); echo "${a[@]}";
a b c d

The string is expanded, passed into read, and then eval'd. So expansions are happening twice here assuming it's double not single quoted.

Another example pre-initializing the variable in the arithmetic context:

$ while read -r "var[${x:=5}, x++]"; do :; done < <(printf '%s\n' {a..c}); for i in "${!var[@]}"; do printf '(%d, %s), ' "$i" "${var[$i]}"; done;
(5, a), (6, b), (7, c), (8, ),

However, if that's all there was to it you wouldn't expect this to work:

while read -r "var[$((x++))]"; do ...

There's some unique evaluation mode going on here since Bash knows not to perform arithmetic expansion before passing the resulting string into read otherwise the result would simply be to make all assignments to var[0].

PS... the preview is deleting all the "pluses". Hopefully the above is understandable.

Jan Schampera, 2011/09/20 17:38


sorry for the delay :-)

This is not "double-expansion" per se, the behaviour is completely understandable (but I think you know it).

Thanks for this very interesting spotlight, I never thought that much about it!

Grisha, 2015/09/04 06:45
Bash knows not to perform arithmetic expansion before passing the resulting string into read

That's because read is part of the while command, so expansions do not happen until the command is executed for each loop iteration.

Andor, 2012/06/06 14:46

Read, has some gotchas.

Jan Schampera, 2012/07/01 11:43

Yes, it's not related directly to read, but to Bash's design regarding pipelining. AFAIR, there was a discussion on the mailing list to align the behaviour to what Korn does - running the last element of a pipeline in the current execution environment.

ABS is a good collection and a good work showing how to use the shell, but don't over-estimate it's technical side.

scavenger, 2013/02/18 09:49, 2013/12/31 09:32

thank you bash for running a sub-shell when piping, now we cannot read anymore multiple variables at the same time !

grep -w regexp file | read a b c

there is no solution to replace this KSH functionality. The command: read -r a b c «<$(command) solution is bourne and korn shell (88 & 93) incompatible.

dannysauer, 2016/05/26 15:42

Both bash and ksh93 can do process substitution like read a b c < <(some command) (note that there is a space between the first <, which redirects STDIN, and the second <, which indicates to run the command and connect it to a named pipe, providing the pipe in place of the <(cmd) expression).

You can use that in place of a pipe pretty much any time. I use it all the time for things like diff <(sort file1 | grep -v '^#') <(sort file2 | grep -v '^#'), which compares two files, ignoring comments and sorting the lines in the files before comparing. :)

BobD, 2015/01/12 17:42

scavenger, how about?–

echo a b c | read -r -a a ; echo ${a[@]} ${#a[@]}

a b c 3

You could leave a comment if you were logged in.
  • commands/builtin/read.1294121113.txt
  • Last modified: 2011/01/04 06:05
  • by thebonsai