Input/output redirection in Linux is a way to control where the input for a command comes from and where the output goes. It involves three main streams:
- Standard Input (stdin): This is where a command gets its input from, typically the keyboard.
- Standard Output (stdout): This is where a command sends its output, typically the terminal screen.
- Standard Error (stderr): This is where a command sends error messages, also typically the terminal screen.
Input Redirection: It involves changing where a command gets its input from. We use the <
symbol for this purpose.
Example
cat < file.txt
This command tells cat
to take its input from file.txt
instead of waiting for input from the keyboard.
Output Redirection: It involves changing where a command sends its output. We use the >
symbol for this purpose.
Example:
ls > files.txt
This command tells ls
to send its output (list of files) to a file named files.txt
instead of displaying it on the screen.
Combining Input and Output Redirection: We can also combine input and output redirection.
Example:
sort < unsorted.txt > sorted.txt
This command tells sort
to take its input from unsorted.txt
and send its output (sorted content) to a file named sorted.txt
.
In summary, input/output redirection allows us to control where a command gets its input from and where its output goes, making it easier to automate tasks and manage files efficiently.
Real-life Example:
Imagine you’re a librarian and you need to categorize books. You have a pile of unsorted books (input) and shelves where you want to organize them (output). Using input/output redirection is like instructing someone to take books from the pile and place them on the shelves without you needing to physically move each book yourself. You’re directing the flow of books (data) without actively handling each one.In summary, input/output redirection in Linux is like controlling the flow of data in the terminal, allowing us to automate tasks and manage files efficiently.