Standart Unix Files, stdin, stdout, stderr, I/O Redirection

Everything is a file. A file can be a collection of data on disk; but in more general terms, a file is an endpoint on a path taken by data.

When you write to a file, you’re sending data along a path to an endpoint. When you read from a file, you are accepting data from an endpoint.

The path that the data takes between files may be entirely within a single computer, or it may be between computers along a network of some kind. Data may be processed and changed along the path, or it may simply move from one endpoint to another without modification.

The "everything is a file" dictum applies to more than collections of data on disk. Your keyboard is a file: it’s an endpoint that generates data and sends it somewhere. Your display is a file: it’s an endpoint that receives data from somewhere and puts it where you can see it.

Table below shows the three standard files defined by Unix/Linux. These files are always open to your programs while the programs are running.



At the bottom of it, a file is known to the operating system by its file descriptor, which is just a number. The first three such numbers belong to the three standard files. When you open an existing file or create a new file from within a program, Linux will return a file descriptor value specific to the file you’ve opened or created. To manipulate the file, you call into the operating system and pass it the file descriptor of the file you want to work with.

I/O Redirection

By default, standard output goes to the display (generally a terminal emulator window), but that’s just the default. You can change the endpoint for a data stream coming from standard output. The data from standard output can be sent to a file on disk instead.

By default, input to your programs comes from the keyboard, but all the keyboard sends is text. This text could also come from another text file. Switching the source of data sent to your programs is no more difficult than switching the destination of its output. The mechanism for doing so is called I/O redirection.

All of Linux’s basic shell commands send their output to standard output. The ls command, for example, sends a listing of the contents of the working directory to standard output.

The ">" symbol is one of two redirection operators.
ls > dircontents.txt

The "<" symbol works the other way, and redirects standard input away from the keyboard and to another file, typically a text file stored on disk.