Saving Output from a Command

Problem

You want to keep the output from a command by putting it in a file.

Solution

Use the > symbol to tell the shell to redirect the output into a file. For example:

$ echo fill it up
fill it up
$ echo fill it up > file.txt
$

Just to be sure, let’s look at what is inside file.txt to see if it captured our output:

$ cat file.txt
fill it up
$

Discussion

The first line of the example shows an echo command with three arguments that are printed out. The second line of code uses the > to capture that output into a file named file.txt, which is why no output appears after that echo command.

The second part of the example uses the cat command to display the contents of the file. We can see that the file contains what the echo command would have otherwise sent as output.

The cat command gets its name from the longer word concatenation. The cat command concatenates the output from the several files listed on its command line, as in: cat file1 filetwo anotherfile morefiles—the contents of those files would be sent, one after another, to the terminal window. If a large file had been split in half then it could be glued back together (i.e., concatenated) by capturing the output into a third file:

$ cat first.half second.half > whole.file

So our simple command, cat file.txt, is really just the trivial case of concatenating only one file, with the result sent to the screen. That is to say, while cat is capable of more, its primary use is to dump the contents of a file to the ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.