Harness the Combinatoric Power of Command-Line Tools and Utilities

../Videos

Saving Output to Files

Bash

Published February 2, 2021

Redirecting the output of programs to files.

Transcript

Let’s look at saving program output to files with shell redirection.

You’ve seen how to create a new file with the echo command before:

echo "Hello there." > hello.txt

The echo command prints its output to “standard output”. Standard output is an abstract way that programs can talk to the OS. A long time ago, programs needed to speak directly with the input and output devices. Unix-based systems created three abstract streams. Standard Output, Standard Input, and Standard Error. Programs can write to those streams instead of talking to your hardware. And you can manipulate the data in those streams.

The “greater than” sign is a shortcut for the standard output stream.

You can use this approach to capture any program output. For example, you can capture the processes running on your machine:

ps -ef > processes.txt

Or even the diagram of an entire directory structure with the tree command:

tree /usr/bin > diagram.txt

A single greater than sign (>) overwrites the file.

echo "Hi there." > diagram.txt
cat diagram.txt
Hi there.

You have to be careful with this, because you won’t get any chance to confirm that you want to overwrite the file. And if you type the wrong filename you may find you’ve accidentally erased something you needed.

Use two greater than signs (>>) to append text to a file. Let’s capture the files and disk usage of the /usr/bin directory:

tree /usr/bin > usage.txt
echo "---" >> usage.txt
du -h /usr/bin >> usage.txt

The tree command saves the diagram to the usage.txt file. Then we use echo to append a dashed line to the file using the two greater than signs. Finally, we use du to get the disk usage and append its output to the file.

Let’s look at the last few lines of the file using tail:

tail usage.txt
├── xzmore
├── yes
├── zdump
├── zipdetails
├── zipgrep
└── zipinfo

0 directories, 824 files
---
145M    /usr/bin/

You can see the output of the tree command, the dashes we added with echo, and the disk usage from du, all in the same file.

That’s just a small piece of what you can do with standard out redirection.