tar is a computer software utility for collecting many files into one archive file.Tar saves many files together into a single tape or disk archive, and can restore individual files from the archive. Normally it used for distribution or backup purposes. It is most popular tool in Linux systems to create compressed archive files.

In this very blog you gonna learn that how to use tar command for data archive and its compression using (tar, tar.gz, tar.bz2).

We gonna use following tar tools.

  • Tar
  • Gzip
  • Bzip2

Create a tar Archive File

So, in following example we gonna create a tar archive file boot.tar for a directory boot in current working directory.

tar -cvf boot.tar -P boot
ls

c – Creates a new .tar archive file.
v – Verbosely show the .tar file progress.
f – File name type of the archive file.
-p Removing leading `/’ from member names

Untar (Un-Compress) Archive File

Now, we gonna un-compress boot.tar archive file in current working directory using follow command

tar -xvf boot.tar boot

Now we will move this directory in desktop as we have compressed boot folder.

mv boot.tar /root/Desktop

So, let say want to un-compress archive in different path or directory. Use -C (Capital C switch) in command and specify your path to uncompress it, Please check below example command.

tar -xvf boot.tar -C /media
ls /media

You can see in above image that boot directory is uncompressed in /media directory.

Create tar.gz Archive File

If you want to compress a file/folder with gzip, then you have to use “z” in tar command and make archive extension as .tar.gz

z – To create a compressed gzip archive file

Run following command

tar -zcvf data.tar.gz data

Un-compress gzip archive file in your desired directory

tar -xvf data.tar.gz -C Desktop

Create tar.bz2 Archive File

The bz2 feature is used to highly compress and create archive. Its archive size is small then gzip archive. The bz2 compression takes more time to compress and decompress files as compared to gzip which takes less time.

j – To create highly compressed tar file, Use following command

tar -cvjSf example.tar.bz2 example

Un-compress bz2 archive file.

tar -xvf example.tar.bz2

Now, un-compress it in another directory

tar -xf example.tar.bz2 -C example

List Content of Archive File

t – it is used to list archive data without extract it.

That’s about it.