Categories
Linux Tutorial Series

Linux Tutorial Series – 53 – Input/output redirection

Here is the video version, if you prefer it:

Because the computer deals with rather abstract notions of input and output streams (where the streams can be the keyboard (for input), a file (for both input and output), a computer screen (for output)), you can actually redirect the output of some of the commands you run.

Say you run cat on a file and the file is large. Your Terminal window will get very messy with the cat output. Instead, you can redirect the cat’s output like so:

cat largeFile > output.txt

Voila. Now you can look at the cat output at your convenience, as it is stored in output.txt.

I will now cover some stuff in regard to input and output redirection. Let’s dive in:

  • cat largeFile > output.txt would override a file named output.txt if it already existed. (Shotts, 2019)⁠ To append to a file that exists (and not override it), use cat largeFile >> output.txt. By the way, appending means adding at the end of an existing file.
  • To redirect standard error in the same file as the standard output (standard error and standard output are separated by default), use the &>, like so: cat largeFile &> output.txt; to append, use &>>
  • You can just redirect standard error somewhere using 2>, as in cat largeFile 2> errors.txt, but I have pretty much never used this.
  • To make a command read input from a file (and not from a keyboard), you use <; this doesn’t make much sense with cat, but it does with some other commands. Just remember that it is possible to redirect standard input as well.

By the way, if you are wondering why is redirecting standard error equal to writing 2>, that’s because standard input, standard output and standard error have numbers associated with them; for standard error it is 2.

And there you have it. To be completely honest with you, I haven’t used input/output redirection much on the command line, other than logging the output of some program to a file. I have used pipelines much more and you will learn about it in some other post.

Signing off till then, hope you learned something useful!

References

Shotts, W. (2019). The Linux Command Line, Fifth Internet Edition. Retrieved from http://linuxcommand.org/tlcl.php. Pages 79-83

NewsletterUpdates on interesting things I am doing

Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.

Leave a Reply

Your email address will not be published.