tar Command in Linux with Options and Examples

What is tar?

tar command is used to gather large sets of files into single file (archive). There are 3 ways to archive files and these are gzip, bzip2 or xz.

There are some action required when using tar command.
  • c (Create an archive)
  • t (list the content of an archive)
  • x (extract an archive)
There are some commonly used options are,
  • f file name (file name of the archive)
  • v (verbosity; useful to see which files get added)

Syntax to archive files

tar [options] archive_file_names files
Ex. tar cf archive.tar file1 file2 file3
Explanation: c for create archive and f file file name. In above example archive.tar is the name of archive file and file1 file2 file3 are file names which gathered in archive file.eck archived file
We can see archived file using ls command. See following way to:
ls archive.tar
archive.tar is the name of archived file.

List contents of a tar archive

tar tf archive.tar
Here, t for list the content of an archive and f is the name of file.

How to extract archive file

tar xf file_name
Ex. tar xf archive.tar
Here, x is used to extract archive file and f is name of file.

How to Create Compressed tar archive

One of the following tar options are specified to create compressed tar archive
  1. z for gzip compression. (filename.tar.gz)
  2. j for bzip2 compression (filename.tar.bz2)
  3. J for xz compression (filename.tar.xz)
There are some example of how to create compressed tar archive.
gzip compression:
tar czf /root/backup.tar.gz /etc
Here, c for create, z for gzip compression, f for filename. /root/backup.tar.gz is name which become gzip compressed file and /etc is a file which gathered in gzip compressed file.

bzip2 compression:
tar cjf /root/backup.tar.bz2 /etc
j for bzip2 compression, and use .bz2 extension for bzip2 compression.

xz compression:
tar cJf /root/backup.tar.xz /etc
J is used to create xz compression file and use .xz extension.

Extract a compressed tar archive

x option is used to extract compressed tar archive.

How extract gzip tar archive
tar xzf /root/backup.tar.xz
x is used for extract file.

How to extract bzip2 file
tar xjf /root/backup.tar.xz

How to extract xz file
tar xJf /root/backup.tar.xz
 

Most Reading