Have you ever wished you could control where the output of your Bash commands goes? Or maybe you’ve wanted to feed a command input from a file instead of your keyboard? Well, with file redirection, you can! This powerful Bash feature lets you manipulate standard input (stdin), standard output (stdout), and standard error (stderr) to your heart’s content.
The Basics: stdin, stdout, and stderr
Before we dive in, let’s cover the basics. Every process running in your Bash shell has three files open by default:
- File 0 (stdin): Where the process gets its input. Normally, this is your keyboard.
- File 1 (stdout): Where the process sends its normal output. This is usually your terminal window.
- File 2 (stderr): Where the process sends error messages. Also typically goes to your terminal.
Redirecting Output with > and >>
The >
symbol is your redirection workhorse. Here’s how it works:
command > file
: Redirects stdout tofile
, overwriting its contents if it exists.command 2> file
: Redirects stderr tofile
, overwriting if it exists.command &> file
: Redirects both stdout and stderr tofile
.
Example:
Want to append to a file instead of overwriting? Use >>
:
command >> file
: Appends stdout tofile
.command 2>> file
: Appends stderr tofile
.
Redirecting Input with <
The <
symbol does the opposite – it takes input from a file instead of your keyboard:
Piping Commands with |
The pipe symbol (|
) lets you chain commands together, sending the output of one command to the input of another.
Example:
To send both stdout and stderr into the pipe, use 2>&1 |
.
Here Documents: Input Right in Your Script
With <<
, you can embed input directly within your script:
Conclusion
File redirection opens up a world of possibilities. You can manipulate file descriptors, open and close files within scripts, and much more.