Go backward to File/Pipe Redirection.
Go up to Redirection.
Closing Output Files and Pipes
When a file or pipe is opened, the file name or command associated
with it is remembered by `awk' and subsequent writes to the same file or
command are appended to the previous writes. The file or pipe stays
open until `awk' exits. This is usually convenient.
Sometimes there is a reason to close an output file or pipe earlier
than that. To do this, use the `close' function, as follows:
The argument FILENAME or COMMAND can be any expression. Its value
must exactly equal the string used to open the file or pipe to begin
with--for example, if you open a pipe with this:
print $1 | "sort -r > names.sorted"
then you must close it with this:
close("sort -r > names.sorted")
Here are some reasons why you might need to close an output file:
* To write a file and read it back later on in the same `awk'
program. Close the file when you are finished writing it; then
you can start reading it with `getline' (*note Explicit Input with
* To write numerous files, successively, in the same `awk' program.
If you don't close the files, eventually you may exceed a system
limit on the number of open files in one process. So close each
one when you are finished writing it.
* To make a command finish. When you redirect output through a pipe,
the command reading the pipe normally continues to try to read
input as long as the pipe is open. Often this means the command
cannot really do its work until the pipe is closed. For example,
if you redirect output to the `mail' program, the message is not
actually sent until the pipe is closed.
* To run the same program a second time, with the same arguments.
This is not the same thing as giving more input to the first run!
For example, suppose you pipe output to the `mail' program. If you
output several lines redirected to this pipe without closing it,
they make a single message of several lines. By contrast, if you
close the pipe after each line of output, then each line makes a
`close' returns a value of zero if the close succeeded. Otherwise,
the value will be non-zero. In this case, `gawk' sets the variable
`ERRNO' to a string describing the error that occurred.