RackNerd Billboard Banner

How to Save the Output of a Command to a File in Linux Terminal

If you use the Linux terminal regularly, there’s a good chance you’ve needed to save the output of a command. Maybe you want to document system info, troubleshoot a script, or just keep logs. Whatever the reason, Linux makes it easy.

Here’s how to save command output to a file — fast and clean.


1. Use the > Operator for New Files

The simplest way to save output is with the > redirection operator. This creates a new file (or overwrites it if it already exists).

Example:

ls -l > files.txt

This saves the output of ls -l to a file called files.txt. If files.txt already exists, it will be replaced.


2. Use the >> Operator to Append

Need to add to a file instead of replacing it? Use >> to append the output.

Example:

df -h >> system_report.txt

This adds the output of df -h to the end of system_report.txt, keeping existing content intact.


3. Save Both Output and Errors

By default, only standard output (stdout) is saved. If you also want error messages (stderr), you can redirect both.

Example:

some_command > output.txt 2>&1

This sends both stdout and stderr to output.txt.


4. Use tee to Save and Display at the Same Time

Want to see the output on your screen and save it to a file? Use tee.

Example:

ls -al | tee listing.txt

To append instead of overwrite, use:

ls -al | tee -a listing.txt

5. Pro Tip: Timestamp Your Files

For scripts or logs, use timestamps to avoid overwriting files.

Example:

date +%Y%m%d_%H%M%S

Combine that with redirection:

top -n 1 > top_$(date +%Y%m%d_%H%M%S).txt

Final Thoughts

Saving command output is essential for automation, documentation, and debugging. Once you get the hang of redirection and tee, it becomes second nature.

Keep this cheat sheet in mind:

  • > = overwrite
  • >> = append
  • 2>&1 = capture errors
  • tee = save and view

Stay sharp, script smart.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
RackNerd Billboard Banner
0
Would love your thoughts, please comment.x
()
x
Copy link