UNIX commands — Compressing directories and files

 

Overview

This article explains how to compress directories and files on your web server to make it easier to download them to your local computer.

Prerequisites

This article assumes you have created a shell user and are able to log into your server via SSH.

Compressing directories

This section shows how to compress a directory to a .zip, .tar.gz, or .tar.bz file.

Compress to a .zip file

This example uses the zip command to compress a directory named example.com into a new file named example.com.zip. The original directory remains untouched.

[server]$ zip -r example.com.zip example.com

You can use the maximum compression setting (-9), which attempts to compress all files. However, this may be slower:

[server]$ zip -9 -r example.com.zip example.com

Compress to a .tar.gz file

This example uses the tar command to compress a directory named images to a file named image_backup.tar.gz. The original directory continues to exist.

[server]$ tar zcvf image_backup.tar.gz images

Compress to a .tar.bz2 file

This tar command compresses a directory named images to a file named image_backup.tar.bz2. The original directory continues to exist.

[server]$ tar cjvf image_backup.tar.bz2 images

What command compresses a directory the most?

The examples below show how much a WordPress site is compressed using the different compression options. First, check the size of the WordPress directory. The original size is 82M.

[server]$ du -sh example.com
82M example.com

The following are the results of the different compression methods.

[server]$ du -sh example.com.zip
30M example.com.zip
[server]$ du -sh example.com.tar.gz 27M example.com.tar.gz
[server]$ du -sh example.com.tar.bz2 24M example.com.tar.bz2

Overall, tar.bz2 compresses the most.

Confirm your directory has been compressed

Once you run the commands above, check to confirm the directory has been compressed. You can do this using du -sh for both the old and new directories.

[server]$ du -sh example.com.zip
30M example.com_backup
[server]$ du -sh example.com 82M example.com

You can see above that the compressed backup is smaller in size than the original directory.

Compressing files

The examples below use gzip to compress a file.

Compress and rename a file

This command compresses a file named test.log while renaming it to test.log.gz. Please note that because the original file was renamed, it no longer exists.

[server]$ gzip test.log

Copy and compress a file

If you still need the test.log file to exist, run the following instead. This uses the -c flag to create a gzipped copy of the file:

[server]$ gzip -c test.log > test.log.gz

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?