DEV Community

Cover image for Compressing and Archiving Files with tar: Examples and Tips
k1lgor
k1lgor

Posted on • Updated on

Compressing and Archiving Files with tar: Examples and Tips


Introduction

The tar command is one of the most commonly used tools in Linux for compressing and archiving files. With tar, you can combine multiple files into a single archive file, and also extract files from an archive. In this blog post, we'll explore the basics of the tar command, as well as some advanced techniques and examples to help you get the most out of this powerful tool.

Basic Usage

The most basic use of tar is to create an archive file from one or more files. For example, to create an archive named "example.tar" from two files named "file1.txt" and "file2.txt", you would use the command:

tar -cvf example.tar file1.txt file2.txt
Enter fullscreen mode Exit fullscreen mode

Image 1

Image 2

The options used in this command are: c for create, v for verbose (displays the names of files being added to the archive), and f for file, which specifies the name of the archive to be created.

Compression Options

By default, tar does not compress the archive file. However, you can specify a compression format to be used with the z or -gzip option for gzip compression, or the j or -bzip2 option for bzip2 compression.

For example, to create a gzip-compressed archive named "example.tar.gz" from two files named "file1.txt" and "file2.txt", you would use the command:

tar -zcvf example.tar.gz file1.txt file2.txt
Enter fullscreen mode Exit fullscreen mode

Image 3

Extracting Files from an Archive

To extract the files from an archive, you can use the x option. For example, to extract the contents of the archive "example.tar", you would use the command:

tar -xvf example.tar
Enter fullscreen mode Exit fullscreen mode

Image 4

The v option can be used to display the names of the files being extracted from the archive.

Listing the Contents of an Archive

To display the contents of an archive without extracting the files, you can use the t option. For example, to list the contents of the archive "example.tar", you would use the command:

tar -tvf example.tar
Enter fullscreen mode Exit fullscreen mode

Image 5

Updating an Archive

To add new files to an existing archive, or update existing files in the archive, you can use the u or -update option. For example, to add a file named "file3.txt" to the archive "example.tar", you would use the command:

tar -uvf example.tar file3.txt
Enter fullscreen mode Exit fullscreen mode

Image 6

Conclusion

These are just a few examples of how to use the tar command. With its options for compression and archive updates, tar is a powerful tool for compressing and archiving files in Linux.

Thank you for reading πŸ§‘β€πŸ’»

Stay tuned for more πŸš€

✌️ and logout

Buy Me A Coffee

Top comments (0)