Differences between revisions 7 and 15 (spanning 8 versions)
Revision 7 as of 2007-05-02 22:44:17
Size: 4153
Editor: redondos
Comment:
Revision 15 as of 2008-09-24 17:50:54
Size: 5381
Editor: GreyCat
Comment: add warning about globs in the array-stuffing examples
Deletions are marked like this. Additions are marked like this.
Line 7: Line 7:
    done < "$file"     done < "$file" # or <<< "$var" to iterate over a variable
Line 41: Line 41:
    OIFS=$IFS; IFS=
while read line
    while IFS= read line
Line 46: Line 45:
    IFS=$OIFS
Line 49: Line 47:
As a feature, the {{{read}}} command concatenates lines that end with a backslash '\' character to one single line. To disable this feature, KornShell and ["BASH"] have {{{read -r}}}: As a feature, the {{{read}}} command concatenates lines that end with a backslash '\' character to one single line. To disable this feature, KornShell and ["BASH"], as well as the POSIX standard for the Bourne shell, have {{{read -r}}}:
Line 52: Line 50:
    OIFS=$IFS; IFS=
while read -r line
    while IFS= read -r line
Line 57: Line 54:
    IFS=$OIFS
Line 81: Line 77:
Note the usage of {{{-print0}}} in the find command, which uses NUL bytes as filename delimiters, and {{{-d $'\0'}}} in the read command to instruct it to read all text into the file variable until it finds a NUL byte. By default, find and read delimit their input with newlines; however, since filenames can potentially contain newlines themselves, this default behaviour will split those filenames with newlines up and cause the command block to fail. See [#faq20 FAQ #20] for more details. Note the usage of {{{-print0}}} in the find command, which uses NUL bytes as filename delimiters, and {{{-d $'\0'}}} in the read command to instruct it to read all text into the file variable until it finds a NUL byte. By default, find and read delimit their input with newlines; however, since filenames can potentially contain newlines themselves, this default behaviour will split those filenames with newlines up and cause the command block to fail. See [:BashFAQ/020:FAQ #20] for more details.
Line 83: Line 79:
Using a pipe to send find's output into a while loop places the loop in a ''subshell'' and may therefore cause problems later on if the commands inside the body of the loop attempt to set variables which need to be used outside the loop; in that case, see [#faq24 FAQ 24], or use process substitution like: Using a pipe to send find's output into a while loop places the loop in a ''subshell'' and may therefore cause problems later on if the commands inside the body of the loop attempt to set variables which need to be used outside the loop; in that case, see [:BashFAQ/024:FAQ 24], or use process substitution like:
Line 91: Line 87:
Sometimes it's useful to read a file into an array, one array element per line. You can do that with the following example: Sometimes it's useful to read a file into an [:BashFAQ/005:array], one array element per line. You can do that with the following example:
Line 95: Line 91:
    # Warning: breaks if lines contain "*" or similar
Line 103: Line 100:
    # Same warning as the previous example
Line 105: Line 103:
Of course, this will blow up in your face if the filenames contain newlines; see [#faq20 FAQ 20] for hints on dealing with such filenames. Of course, this will blow up in your face if the filenames contain newlines; see [:BashFAQ/020:FAQ 20] for hints on dealing with such filenames.

Both of these array-stuffing examples fail if the shell encounters a [:glob:] that matches files in the current directory as one of the input lines. Glob expansion can be disabled with `set -f` and then re-enabled afterward with `set +f` if needed. For more details on arrays, see [:BashFAQ/005:FAQ 5].

On the other hand, if the file lacks a trailing newline (such as {{{/proc/$$/cmdline}}} on Linux), the line will not be printed by a {{{while read ...}}} loop, as {{{read}}} returns a failure that aborts the while loop, thus failing to print the ultimate line:

{{{
    # This does not work:
    echo -en 'line 1\ntruncated line 2' | while read line; do echo $line; done

    # This does not work either:
    echo -en 'line 1\ntruncated line 2' | while read line; do echo "$line"; done; echo "$line"

    # This works:
    echo -en 'line 1\ntruncated line 2' | (while read line; do echo "$line"; done; echo "$line")
}}}
For a discussion of why the second example above does not work as expected, see [:BashFAQ/024:FAQ #24].

Anchor(faq1)

How can I read a file line-by-line?

    while read line
    do
        echo "$line"
    done < "$file"          # or   <<< "$var"    to iterate over a variable 

If you want to operate on individual fields within each line, you may supply additional variables to read:

    # Input file has 3 columns separated by white space.
    while read first_name last_name phone; do
      ...
    done < "$file"

If the field delimiters are not whitespace, you can set IFS (input field separator):

    while IFS=: read user pass uid gid gecos home shell; do
      ...
    done < /etc/passwd

Also, please note that you do not necessarily need to know how many fields each line of input contains. If you supply more variables than there are fields, the extra variables will be empty. If you supply fewer, the last variable gets "all the rest" of the fields after the preceding ones are satisfied. For example,

    while read first_name last_name junk; do
      ...
    done <<< 'Bob Smith 123 Main Street Elk Grove Iowa 123-555-6789'
    # Inside the loop, first_name will contain "Bob", and
    # last_name will contain "Smith".  The variable "junk" holds
    # everything else.

The read command modifies each line read, e.g. by default it removes all leading whitespace characters (blanks, tab characters, ... -- basically any leading characters present in IFS). If that is not desired, the IFS variable has to be cleared:

    while IFS= read line
    do
        echo "$line"
    done < "$file"

As a feature, the read command concatenates lines that end with a backslash '\' character to one single line. To disable this feature, KornShell and ["BASH"], as well as the POSIX standard for the Bourne shell, have read -r:

    while IFS= read -r line
    do
        echo "$line"
    done < "$file"

Note that reading a file line by line this way is very slow for large files. Consider using e.g. ["AWK"] instead if you get performance problems.

One may also read from a command instead of a regular file:

    some command | while read line; do
       other commands
    done

This method is especially useful for processing the output of find with a block of commands:

    find . -print0 | while read -d $'\0' file; do
        mv "$file" "${file// /_}"
    done

This command reads one filename at a time from the file command and renames the file so that its spaces are replaced by underscores.

Note the usage of -print0 in the find command, which uses NUL bytes as filename delimiters, and -d $'\0' in the read command to instruct it to read all text into the file variable until it finds a NUL byte. By default, find and read delimit their input with newlines; however, since filenames can potentially contain newlines themselves, this default behaviour will split those filenames with newlines up and cause the command block to fail. See [:BashFAQ/020:FAQ #20] for more details.

Using a pipe to send find's output into a while loop places the loop in a subshell and may therefore cause problems later on if the commands inside the body of the loop attempt to set variables which need to be used outside the loop; in that case, see [:BashFAQ/024:FAQ 24], or use process substitution like:

    while read line; do
        other commands
    done < <(some command)

Sometimes it's useful to read a file into an [:BashFAQ/005:array], one array element per line. You can do that with the following example:

    O=$IFS IFS=$'\n' arr=($(< myfile)) IFS=$O
    # Warning: breaks if lines contain "*" or similar

This temporarily changes the Input Field Separator to a newline, so that each line will be considered one field by read. Then it populates the array arr with the fields. Then it sets the IFS back to what it was before.

This same trick works on a stream of data as well as a file:

    O=$IFS IFS=$'\n' arr=($(find . -type f)) IFS=$O
    # Same warning as the previous example

Of course, this will blow up in your face if the filenames contain newlines; see [:BashFAQ/020:FAQ 20] for hints on dealing with such filenames.

Both of these array-stuffing examples fail if the shell encounters a [:glob:] that matches files in the current directory as one of the input lines. Glob expansion can be disabled with set -f and then re-enabled afterward with set +f if needed. For more details on arrays, see [:BashFAQ/005:FAQ 5].

On the other hand, if the file lacks a trailing newline (such as /proc/$$/cmdline on Linux), the line will not be printed by a while read ... loop, as read returns a failure that aborts the while loop, thus failing to print the ultimate line:

    # This does not work:
    echo -en 'line 1\ntruncated line 2' | while read line; do echo $line; done

    # This does not work either:
    echo -en 'line 1\ntruncated line 2' | while read line; do echo "$line"; done; echo "$line"

    # This works:
    echo -en 'line 1\ntruncated line 2' | (while read line; do echo "$line"; done; echo "$line")

For a discussion of why the second example above does not work as expected, see [:BashFAQ/024:FAQ #24].

BashFAQ/001 (last edited 2024-11-07 03:19:23 by GreyCat)