How to compress files with tar command on Linux/Unix

Posted on in Categories , , last updated October 23, 2017

How do I compress a directory or files on a Linux or Unix like system using tar command?

An archive file is nothing but a collection of files and directory stored in one file. Please note that by default the archive file is not compressed. A compressed file uses less disk space.
tar compress command
This quick page explains how to compress, list and extract files using the tar command on Linux or Unix-like system.

Archiving files at the shell prompt

The tar command is as follows:
tar -cvf fileName.tar file1 file2 file3
tar -cvf fileName.tar dir1 dir2 dir3
tar -cvf fileName.tar file1 dir1


  • c : Create a new archive
  • v : Verbose output
  • f : Use given archive file or device such as /dev/st0


For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /home/vivek/Documents into the archive file docs.tar verbosely listing the files being archived:
$ tar -cvf docs.tar /home/vivek/Documents/
Sample outputs:

 tar: Removing leading `/' from member names
/home/vivek/Documents/info-needed/Shipment invoice.pdf
/home/vivek/Documents/Scanned Document.pdf

The following adds file named /etc/resolv.conf, /etc/hosts, and /home/vivek/project1 directory:
$ tar -cvf backup.tar /etc/resolv.conf /etc/hosts /home/vivek/project1

Compressing Files at the Shell Prompt

For compressing files you need to use the compression utilities:

  1. bzip2 – tar.bz2 file
  2. gzip – tar.gz file
  3. zip – file

To compress the tar file with gzip pass the -z option, run:
$ tar -cvzf docs.tar.gz /home/vivek/Documents/
To compress the tar file with bzip2 pass the -j option, run:
$ tar -cvzf docs.tar.bz2 /home/vivek/Documents/

To list the contents of a tar file, enter:

$ tar -tvf docs.tar
$ tar -tvzf docs.tar.gz
$ tar -tvjf docs.tar.bz2

To extract the contents of a tar file, enter:

$ tar -xvf docs.tar
$ tar -xvzf docs.tar.gz
$ tar -xvjf docs.tar.bz2


  • t : List the contents of an archive
  • x : Extract a tar archive
  • z : Compress the tar file with gzip
  • j : compress the tar file with bzip2

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 0 comments/add one below):