How to archive and extract files and folders using Tar

"Tar" is program used archiving (and then later extracting) files and folders.

Tar does not compress files.

Instead, Tar files are often compressed using a program like Zip (even though Zip can compress and archive).

Note: You must decompress the Zip (or Gzip or Bzip2 or whatever) file and then extract the resulting Tar file. Once a Tar file has been compressed, you can not arbitraily extract files.

Sometimes you may prefer archiving files using Tar and then compressing the resulting file.

Zip compresses files seperately so creating a Tar file means multiple files will be treated as one big file and then compressed more efficiently.

Here's an analogy:

Imagine you have two files, but we'll pretend their sheets of paper.

Each page has the phrase, "All work and no play makes Jack a dull boy", repeated twenty times. And the same is true for the second page.

Zip would compress the first page by retaining the first instance of the phrase "All work and no play makes Jack a dull boy" and then discarding the redundancies (while also noting that the phrase should be repeated 20 times).

"All work and no play makes Jack a dull boy" x 20 (lines)

And then Zip would look at the next page and reach the same conclusion.

"All work and no play makes Jack a dull boy" x 20 (lines)

The zip file would contain two lines:

All work and no play makes Jack a dull boy" x 20 (lines) 
All work and no play makes Jack a dull boy" x 20 (lines) 

Combining those two pages (files) into a Tar archive means Zip will analyze all the pages/files (data) since its just one big file. Zip would then recognize that "All work and no play makes Jack a dull boy" appears 20 times on one page and then 20 times on another page.

The compressed Tar file would then look something like this:

All work and no play makes Jack a dull boy" x 20 (lines) x 2 (pages)

The new line is a bit longer than the previous lines of data, but it uses way less data in total.

Remember every character is data that needs to be stored. Based on the example, the amount of data stored using Tar + Zip is almost half of what's used by using Zip alone.

This is a super simplistic explanation of how compression works, but hopefully it was heplful.

Archiving

Syntax

tar czvf [tarfile] [filepath]

Example

tar czvf backup.tar.gz archive/

C (Compress) – Creates the new archive.
Z (Zip) – Compresses the file.
F (File) – The compressed file has been given a name.
V (Verbose) – Detailed list of actions

Extracting

Syntax

tar -xzf [name].tar.gz

Example

tar -xzf foo.tar.gz