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:
|
|
Here:
-c
stands for create-v
stands for verbose (optional; provides detailed output)-f
specifies the tarball file name
To extract the contents of a tarball, use:
|
|
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:
|
|
In this case:
-z
specifies gzip compression- The resulting file will have the extension
.tar.gz
You can use -j
instead of -z
for bzip2 compression, resulting in a .tar.bz2
extension.
To extract a compressed tarball, use:
|
|
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:
|
|
You can also preserve the permissions and ownership of directories while extracting a tarball using the --preserve-permissions
and --same-owner
options like so:
|
|
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:
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:
--listed-incremental
: Creates incremental backups--wildcards
: Enables the usage of wildcard patterns--totals
: Shows total bytes of each transferred file--ignore-zeros
: Ignores zeroed blocks in the archive--show-transformed-names
: Displays the transformation used for file names
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!