Course


Archive, compress, unpack, and uncompress files

Learn how to archive, compress, unpack, and uncompress files using tar, gzip, and bzip2.

Introduction

In this lesson we will show and tell two popular methods of compress and uncompress files and folders: tar and gzip.

Command tar

The program called tar can be used to backup/compress and transfer files/folders easily. With tar you can archive as well as compress. Before using tar there are a few flags you want to be familiar with.

  • -c flag = Create a new archive.
  • -v flag = Verbosely list files processed.
  • -f flag = The archive file.
  • -x flag = Extract files from an archive.
  • -j flag = Filter the archive through bzip2.
  • -z flag = Filter the archive through gzip.
  • -C flag = Uncompress/extract to a defined directory.

Lets say we have a folder filled with files that we want to archive. To do so we simply do the following.

The above command creates a file named archive.tar full of all of the files and directories within the /tmp directory (store it in the HOME folder of the user root which can be accessed via the ~/) . The -c allows the tar utility to know that we want to create a new archive. The -v flag allows us to see the progress of the archive and what files it is currently processing. The -f flag allows you to create the name of the file you want to create. In this case its archive.tar.

Let's now compress the archive using bzip2:

Similar to the above commands which we learned you can easily uncompress files by using the -x flag instead of the -c flag. For instance to unarchive a standard tar file do the following.

In order to decompress a gzip file use the -z flag along with the -x flag.

Command gzip and gunzip

You can also use gzip and gunzip to compress and decompress files like tar. Here’s an example below on how to use gzip to compress a file. See -c option and the redirection > used to store the file in the /root folder.

In order to decompress the file you can use gunzip as such. After the decompression is complete the compressed file is then removed.