Compressing Files

Problem

You need to compress some files and aren’t sure of the best way to do it.

Solution

First, you need to understand that in traditional Unix, archiving (or combining) and compressing files are two different operations using two different tools, while in the DOS and Windows world it’s typically one operation with one tool. A “tarball” is created by combining several files and/or directories using the tar (tape archive) command, then compressed using the compress, gzip, or bzip2 tools. This results in files like tarball.tar.Z, tarball.tar.gz, tarball.tgz, or tarball.tar.bz2. Having said that, many other tools, including zip, are supported.

In order to use the correct format, you need to understand where your data will be used. If you are simply compressing some files for yourself, use whatever you find easiest. If other people will need to use your data, consider what platform they will be using and what they are comfortable with.

The Unix traditional tarball was tarball.tar.Z, but gzip is now much more common and bzip2 (which offers better compression than gzip) is gaining ground. There is also a tool question. Some versions of tar allow you to use the compression of your choice automatically while creating the archive. Others don’t.

The universally accepted Unix or Linux format would be a tarball.tar.gz created like this:

$ tar cf tarball_name.tar directory_of_files
$ gzip tarball_name.tar

If you have GNU tar, you could use -Z for compress (don’t, this is obsolete), ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.