In our previous lesson, we learned about redirecting the standard output (stdout) stream. Similarly, we can also manage the standard input (stdin) stream. By default, a program receives its stdin from the keyboard, but we can also use files or the output from other processes as an input source.
Understanding stdin and stdout
Every command-line process in Linux operates with at least two fundamental data streams: standard input (stdin) and standard output (stdout). A program reads data from stdin and writes its results to stdout. Understanding how to control both stdin and stdout is crucial for effective command-line work.
How to Redirect stdin
Just as we use > for stdout redirection, we use the < operator to redirect stdin. This powerful feature allows you to tell a command to read its input from a file instead of waiting for you to type it on the keyboard. This is a core concept of input redirection.
Practical Example with cat stdin
Let's revisit the peanuts.txt file from the previous lesson, which contains the text "Hello World". Consider the following command:
cat < peanuts.txt > banana.txt
Here’s a breakdown of what happens:
- The
< peanuts.txtpart tells the shell toredirect stdinfor thecatcommand, making it read frompeanuts.txtinstead of the keyboard. - The
catcommand processes its input. In this case, usingcat stdinmeans it reads the content ofpeanuts.txt. - The
> banana.txtpart redirects the standard output ofcatto a new file namedbanana.txt.
Ultimately, the content of peanuts.txt is copied to banana.txt. This example effectively demonstrates how to manage both stdin and stdout in a single, efficient command.