November 3, 2024

How to Create tar.gz File in Linux

A tar archive is a file that stores a collection of directories and files, also known as ‘tarballs’. The tar command stands for ‘tape archiving’ that stores data along with additional information’s such as file ownership, file permissions, SELinux permissions, Directory structure, and timestamp.

A tarball combines multiple files into one archive file, which can be further compressed using a compression algorithm named gzip & bzip2, but gzip is the most widely used algorithm.

A tar archive compressed with gzip ends with the extension .tar.gz or .tgz.

In this post, we’ll see how to compress files and directories with the tar command in Linux with example.

Installing tar.gz

The tar command pre-installed on various Linux-based distributions. however, if it’s not available, you can easily install it using distribution package manager as shown below:

yum install tar gzip    [RHEL 7]
dnf install tar gzip    [RHEL 8/9, Fedora]
apt install tar gzip    [Debian/Ubuntu]
zypper in tar gizp      [OpenSUSE]
pacman -S tar gizp      [Arch Linux]

Syntax of tar command

The common syntax of tar command is given below:

Syntax: tar [Operation Mode[ [Options] [Archive_File_Name.tar.gz] [File or Directory to be Archived]

Creating tar.gz File

Example-1:

Let’s create an archive named ‘backup.tar.gz’ from the '/home/linuxgeek/shell-scripts/' directory. To do so, you need to run the following command. It also compresses the sub-directories of the given directory.

Make a Note: When you create tar.gz in a specific directory you must specify the full path of the directory in the tar command.

tar -cvzf backup.tar.gz /home/linuxgeek/shell-scripts/
or
tar -cvzf backup.tgz /home/linuxgeek/shell-scripts/

The tar command uses the following flags to customize the command input:

FlagUsage
-cCreate a new archive
-zUse gzip compression
-vVerbose output
-fSpecifies the archive file name

The compressed backup.tar.gz file is created successfully that can be viewed with ls command.

Creating tar.gz in Linux

Example-2:

If you want to create an archive named ‘data.tar.gz’ from ‘file1’, ‘file2’ and ‘file3’, run: If these files reside elsewhere, you may need to provide the full path to the file.

tar -cvzf data.tar.gz file1 file2 file3
or
tar -cvzf data.tgz file1 file2 file3

The data.tar.gz file is created successfully.

Extracting tar.gz File

To extract existing (or unzip) tar.gz and tgz archives, simple run the following command.

tar -xf backup.tar.gz
or
tar -xf backup.tgz

Wrapping up

The tar is a command line utility used to create an archive file, which can be further compressed using gzip nor bzip2 compression algorithms based on your requirement.

I hope, the above tutorial will help you create tar.gz file and extract tar.gz files on Linux.

Leave a Reply

%d bloggers like this: