Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using tee

Introduction

The tee command is a powerful tool in the command line that reads from the standard input and writes to both standard output and one or more files simultaneously. This can be particularly useful for logging and debugging purposes.

Basic Usage

The basic syntax of the tee command is:

command | tee [options] [file...]

For example, to list the contents of a directory and simultaneously write the output to a file, you can use:

ls -l | tee output.txt

This command will display the directory contents on the screen and also write the same output to output.txt.

Appending to Files

By default, tee overwrites the specified files. To append to a file instead of overwriting it, use the -a option:

echo "New Line" | tee -a output.txt

This command will add the line "New Line" to the end of output.txt without removing the existing contents.

Ignoring Interrupts

If you want tee to ignore interrupts (e.g., Ctrl+C), you can use the -i option:

command | tee -i output.txt

This can be useful if you want to ensure that tee continues to write output to the file even if an interrupt signal is sent.

Using tee with Multiple Files

You can also write output to multiple files by specifying more than one file name:

command | tee file1.txt file2.txt

This command will write the output of command to both file1.txt and file2.txt.

Example: Logging and Displaying Output

Let's consider a practical example where you want to compile a program and log the output while also displaying it on the screen:

make | tee build.log

This command will run the make command, display the output on the screen, and simultaneously write it to build.log.

Conclusion

The tee command is a versatile tool that can be extremely useful for debugging, logging, and monitoring command output. By understanding and utilizing its various options, you can effectively manage and redirect output in your command-line workflows.