Working with .tar and .tar.gz files under Linux

Tar, which is actually derived from 'Tape Archive', is a program that combines multiple files into a single file or "archive" for easy storage. It's most often combined with gzip to compress the tar archive thus creating a .tar.gz file.

In this blog, we will list some of the most common flags for tar and give you a couple of examples of working with the program.

Tar flags

Tar has the following command structure:

tar [flags] [name_of_archive] [files_or_directories_to_be_archived]

Here are some of the most common flags used with tar:

-c : Creates an archive

-x : Extracts the files from the archive

-f : Creates an archive with a specific name

-t : Lists contents of an archive

-t : Lists the files within the archived file

-u : Adds files to an existing archive file

-z : Used to compress or decompress the tar file using gzip

-v : Shows the progress of the process

💡
Note that the -f flag should always be the last as it will be looking for a file name and other flags after it will confuse it.

Archiving files with tar

Here is an example of how to create a tar archive. We have three files: file1, file2, and file3.

We want to create an archive called "archived_files". Here is the command to do that:

tar -cf archived_files.tar file1 file2 file3

Example output:

root@hostname:~# ls
archived_files.tar  file1  file2  file3

Compressing files with tar

We have the same three files however this time we also want to compress the archive. When compressing bigger files it might be a good idea to add the v flag even though it's not necessary so you can keep track of the completion progress of the program.

tar -czvf archived_files.tar.gz file1 file2 file3

Example output:

root@hostname:~# tar -czvf archived_files.tar.gz file1 file2 file3
file1
file2
file3
root@hostname:~# ls
archived_files.tar.gz  file1  file2  file3

Decompressing files with tar

We have the compressed archive "archived_files.tar.gz". We want to decompress it. Here is the command to do so:

tar -xzf archived_files.tar.gz

Listing files inside an archive

To list the contents of a tar archive we use the following command

tar -ztf [archive_name]

The output will look something like this:

root@hostname:~# tar -ztf archived_files.tar.gz
file1
file2
file3

Archiving folder with tar

Let's say we want to archive the whole log folder of our Linux system with all the files inside and compress it so it doesn't take up as much space. To do so we can use the following command

tar -czvf log_archive.tar /var/log

Example output

var/log/
var/log/dpkg.log
var/log/lastlog
var/log/dist-upgrade/
var/log/fontconfig.log
var/log/journal/
var/log/upgrade-policy-changed.log
var/log/btmp
var/log/wtmp
var/log/bootstrap.log
var/log/ubuntu-advantage.log
var/log/private/
var/log/apt/
var/log/apt/history.log
var/log/apt/eipp.log.xz
var/log/apt/term.log
var/log/alternatives.log
var/log/unattended-upgrades/
var/log/faillog