I/O Redirection
Learn how redirection works in Bash.
We'll cover the following...
Redirecting text data
Let’s suppose that we are looking for the files on the disk. We want to save the search results in a file. We use the find
utility and the redirection operator 1>
. Then, the utility call looks like this:
find / -path */doc/* -name README 1> readme_list.txt
We run cat readme_list.txt
to view readme_list.txt
.
Run the commands discussed in this lesson in the terminal below.
The command creates the readme_list.txt
file in the current directory and writes the find
utility’s output there. The file contents look the same because they are printed on the screen without the redirection operator. If the current directory has the readme_list.txt
file already, the command overwrites it.
What does the 1>
operator mean? It’s a redirection of the standard output stream. There are three standard streams in Unix. The table below explains them.
Number | Name | Purpose |
---|---|---|
0 | Standard input stream (stdin). | A program receives input data from this stream. By default, it comes from an input device like a keyboard. |
1 | Standard output stream (stdout). | A program outputs data there. The terminal window prints this stream by default. |
2 | Standard error stream (stderr). | A program outputs the error messages there. The terminal window prints this stream by default. |
Every program operates in the software environment that the OS provides. We can imagine each standard stream as a communication channel between the program and the OS environment.
Early Unix systems used only physical channels for data input and output. The input channel comes from the keyboard. Similarly, the output channel goes to the monitor. Then, developers introduced the streams as an abstraction for these channels.
The abstraction makes it possible to work with different objects using the same algorithm. It allows us to replace a real device input with the file data. Similarly, it replaces the need of printing data on the screen by writing it to the file. The same OS code ...