Compress and decompress files in Linux

Compressing and decompressing files is one of the most common tasks that we are going to have to perform in Linux by command line. We can do it using various tools, but there are two that will be available in almost any distribution.

They are two tools that have to be used in a complementary way. These are tar, which simply packs multiple files into a single file, and gzip, which does the compression itself.

The tar command has the following syntax:

tar

Where options are, for example, the following:

  • c: create a file
  • x: extract from a file
  • t: list the contents of a file
  • v: view a report of actions as they are performed
  • f: pack file contents
  • z: to compress while packing

As you can see, with the z option it can be compressed in the same step as it is packed, which can make things faster and more convenient. Anyway, tar just does the packaging and gzip does the compression. Simply that we don’t have to call gzip, but tar does it directly and internally.

Examples of file compression in Linux

  1. If we want to pack a directory called “html” and save the data in “html-pack.tar”, we would do it with the statement:

tar cvf html-package.tar html

  1. If we want to compress a directory called “files” and save it in a file called “files-comp.tgz”, we could do something like this:

tar czvf files-comp.tgz files

If we look closely, in this case we have given the name of the compressed file a .tgz extension, which indicates that it is packaged and compressed.

See also  Basic HTML5 Document

Examples of commands to unzip the files

  1. If we want to unpack a file called xxx.tar we can use a command like this:

tar xvf xxx.tar

That assumes that we have the xxx.tar file in the same directory from which we launched the command. The contents will be unpacked in the same directory where we are located.

  1. If the file we want to unpack is compressed. That is, if we want to decompress and unpack in a single step, we have to do it with the z option of the tar command. Something like this:

tar xzvf xxx.tgz

With these example commands you will be able to comfortably solve most of the compression and decompression operations in Linux. It’s practically a copy and paste 😉

This other FAQ explains how.

Loading Facebook Comments ...
Loading Disqus Comments ...