How to Create a Tar GZip File from the Command Line

Tags:

You’re probably familiar with making your own zip files if you’ve ever needed to transfer a group of files or if you’re managing your own backups outside of Time Machine. Using the GUI zip tools are easy and user friendly, but if you want some more advanced options with better compression you can turn to the command line to make a tar and gzip archive. The syntax will be the same in Mac OS X as it is in Linux.
Creating a Tar GZip Archive Bundle

From the command line (/Applications/Terminal/), use the following syntax:

tar -cvzf tarballname.tar.gz itemtocompress

For example, to compress a directories jpg files only, you’d type:

tar -cvzf jpegarchive.tar.gz /path/to/images/*.jpg

The * is a wildcard here, meaning anything with a .jpg extension will be compressed into the jpegarchive.tar.gz file and nothing else.

The resulting .tar.gz file is actually the product of two different things, tar basically just packages a group of files into a single file bundle but doesn’t offer compression on it’s own, thus to compress the tar you’ll want to add the highly effective gzip compression. You can run these as two separate commands if you really want to, but there isn’t much need because the tar command offers the -z flag which lets you automatically gzip the tar file.
Opening .tar.gz Archives

Unpacking the gz and tar files can be done with applications like Pacifist or Unarchiver (free), or by going back to the command line with:

gunzip filename.tar.gz

Followed by:

tar -xvf filename.tar

Generally you should untar things into a directory, or the present working directory will be the destination which can get messy quick.