A tar archive is a file that stores a collection of other files, including information about them, such as the ownership, permissions, and timestamp.
In Linux operating systems, you can use the tar
command to create tar archives. The command can also compress archives using a vast range of compression programs with gzip is the most popular algorithm.
By convention, the name of a tar archive compressed with gzip should end with either .tar.gz or .tgz.
This article describes how to create tar.gz files.
Creating tar.gz File
Most Linux distributions come include the GNU version of tar
that supports compressing archives.
The general form of the command for creating tar.gz files is as follows:
tar -czf archive-name.tar.gz file-name...
Here’s what the command options mean:
-c
– instructstar
to create a new archive.-z
– sets the compression method to gzip.-f archive-name.tar.gz
– specifies the archive name.file-name...
a space-separated list of files and directories to be added to the archive.
The user running the command must have write permissions on the directory where the tar.gz file will be created, and read permissions on the files being added.
For example, to create an archive named “archive.tar.gz” from “file1” and “file2” you would use the following command:
tar -czf archive.tar.gz file1 file2
On success, the command doesn’t print any output. To verify that the archive is created, list the directory contents with ls
.
-v
option to make the tar
command more visible and print the names of the files being added to the archive on the terminal.If you want to create the tar.gz in a specific directory, provide a full path to the archive file:
tar -czf /home/user/archive.tar.gz file1 file2
You can create tar.gz files from the contents of one or more directories or files. By default, directories are archived recursively unless --no-recursion
option is specified.
The following example shows how to create an archive named “web_backup.tar.gz” of the /var/www/website
directory:
tar -czf web_backup.tar.gz /var/www/website
If you are running a system that has an older version of tar
that doesn’t support compression, you can use the gzip
command:
tar -czf - file1 file2 | gzip > archive.tar.gz
In the example above, the tar
command outputs the archive to stdout (represented by -
). The archive is piped to gzip
, which compress and write the archive to the disk.
Examples
-
Create a tar.gz file from all “.jpg” files:
tar -czf images.tar.gz *.jpg
The wildcard character (
*
) means all files that end with “.jpg” extension. -
Create a tar.gz file, transfer it over ssh and extract it on the remote machine:
tar cvf - project | ssh user@ip_addr "tar xv -C /var/www"
Conclusion
tar.gz file is a Tar archive compressed with Gzip. To create a tar.gz file, use the tar -czf
command, followed by the archive name and files you want to add.
If you have any questions, please leave a comment below.