Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Linux 'tar' command

May 1, 2024

Mastering the Linux ‘tar’ Command: A Comprehensive Guide with Examples

Introduction

The tar command is an essential tool for managing files and directories in Linux. It allows you to create, view, extract, and manipulate archived files known as “tarballs”. In this blog post, we will explore the various functionalities of the tar command, along with extensive examples to illustrate its usage.

Basic Usage

Before diving into the advanced features, let’s start with the basic usage of tar. To create a tarball, use the following command:

1
tar -cvf archive.tar file1 file2 directory/

Here:

To extract the contents of a tarball, use:

1
tar -xvf archive.tar

Note the -x option for extraction. Again, the -v option is optional, providing verbose output.

Working with Compression

The tar command can also be used with compression tools like gzip and bzip2 to reduce file sizes. To create a compressed tarball, use the following command:

1
tar -czvf archive.tar.gz file1 file2 directory/

In this case:

You can use -j instead of -z for bzip2 compression, resulting in a .tar.bz2 extension.

To extract a compressed tarball, use:

1
tar -xzvf archive.tar.gz

Again, -x specifies extraction, -z specifies gzip decompression, and the -v option provides verbose output.

Working with Directories

The tar command can handle directories in different ways. For instance, to exclude a directory while creating a tarball, use the --exclude option:

1
tar -cvf archive.tar --exclude=directory_to_exclude/ directory/

You can also preserve the permissions and ownership of directories while extracting a tarball using the --preserve-permissions and --same-owner options like so:

1
tar -xvf archive.tar --preserve-permissions --same-owner

Verifying Tarball Integrity

To ensure the integrity of a tarball, you can use the --compare option. It compares the files in the tarball with the actual files on disk:

1
2
3
tar -cvf archive.tar file1 file2

tar -df archive.tar

The second command checks if the contents of archive.tar match the files on disk.

Advanced Usage

The tar command offers many more features to cater to various needs. Some advanced options include:

Refer to the tar man page for more details on these options and other advanced functionalities.

Conclusion

The tar command is a versatile tool for handling archived files in Linux. With the examples provided in this blog post, you should be equipped to create, view, extract, and manipulate tarballs efficiently. Experiment with different options and explore advanced features to make the most out of the Linux tar command.

Happy archiving!


➡️ Esp-IDF: Understanding ESP32's Official Development Framework


⬅️ ESP32 Development Environment: Setting up Arduino IDE for ESP32 Programming


Go back to Posts.