File Redirection in Bash

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 to file, overwriting its contents if it exists.
  • command 2> file: Redirects stderr to file, overwriting if it exists.
  • command &> file: Redirects both stdout and stderr to file.

Example:

save ps command results to ps.out

Want to append to a file instead of overwriting? Use >>:

  • command >> file: Appends stdout to file.
  • command 2>> file: Appends stderr to file.
Appends stdout to file

Redirecting Input with <

The < symbol does the opposite – it takes input from a file instead of your keyboard:

Sort the contents of unsorted_list.txt

Piping Commands with |

The pipe symbol (|) lets you chain commands together, sending the output of one command to the input of another.

Example:

print files content and "grub" and filter for "5"

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:

image 16

Conclusion

File redirection opens up a world of possibilities. You can manipulate file descriptors, open and close files within scripts, and much more.