What Is Input Output Redirection in Linux?
Input and output (I/O) redirection in the Linux command line is a mechanism that allows users to change the default sources of input and destinations for output when running commands. By default, Linux commands receive input from your keyboard and display output or errors directly on your terminal screen. By using redirection operators, you can instruct the shell to read input from a file instead of the keyboard, save command output to a file, or separate error messages from standard output.
The Three Standard Streams
Every command executed in the Linux shell automatically opens three data streams, each identified by a numeric file descriptor (FD):
- Standard Input (
stdin, FD 0): The default stream that provides data to a command, usually originating from the keyboard. - Standard Output (
stdout, FD 1): The default stream that carries the normal output of a command, typically displayed in the terminal window. - Standard Error (
stderr, FD 2): The default stream dedicated to error messages, separated from regular output so diagnostics are not mixed with expected data.
Output Redirection
(stdout)
Output redirection sends the standard output of a command to a file instead of the screen.
- Overwrite (
>): Directs output to a file. If the target file already exists, its contents are overwritten. If it does not exist, a new file is created.ls -l > directory_list.txt - Append (
>>): Directs output to the end of a specified file without deleting existing contents.date >> log.txt
Error Redirection
(stderr)
Because stderr uses file descriptor 2, you must
explicitly reference the descriptor number when redirecting errors.
- Redirect errors only (
2>): Captures error messages to a file.ls /nonexistent-path 2> error.log - Redirect both
stdoutandstderr(&>or2>&1): Combines standard output and error messages into a single destination.command > output.txt 2>&1 # Alternatively: command &> output.txt - Discard output (
/dev/null): Silences errors or output entirely by routing the stream to the null device.command 2> /dev/null
Input Redirection
(stdin)
Input redirection allows a command to read data from a file rather than waiting for keyboard input.
- Redirect standard input (
<): Passes the contents of a file to a program'sstdin.wc -l < data.csv - Here Document (
<<): Allows multi-line input directly from the command line until a specified delimiter is encountered.cat << EOF Line 1 Line 2 EOF
Redirection vs. Pipelines
While redirection operators (<, >,
>>) route streams between commands and files or
devices, the pipe operator (|) connects the standard output
of one command directly into the standard input of another command.
Understanding and combining both techniques allows for powerful and
flexible automation scripts in the Linux shell.