Since I’ve been a web developer, I’ve worked with a significant amount of sites that contain large amounts of assets. Everything from the platform being used to the stylesheets and images used in theme files, the amount of files in a company’s website can really add up. When it comes time to move these files to another server, things can get irritating quickly. Knowing how to compress files via command line will help you out immensely in this type of situation.
Small companies would backup a website just by using FTP. Depending on the size of the client’s website, downloading the entire structure could take hours and disconnections are always possible. This can end up with corrupted data on your end. In my opinion, the simplest way to perform a website backup task is to create a .tar.gz file, or a tarball, of the entire website. This compresses the entire hierarchy into a single file. With this quick tutorial, you’ll learn how to compress files via command line in Linux.
How to Compress a File with Tar
Navigate to the directory of the file you want to archive. Let’s say the file you want to compress is entitled myfile.txt. You would use the following command to compress the file to a tar.gz file:
tar -czvf myfile.tar.gz myfile.txt
Here’s the format of this command:
- tar invokes the compression command
- the -czfv flag will create the archive, compress it with gzip, show output, and let you choose your filename
How to Compress a Directory with Tar
In order to compress a directory to a tar.gz file, the command you’ll be using the same format as before. This time, you’ll be including the directory name instead of the filename. In this scenario, the directory you want to archive is myfiles. The following command will archive the myfiles directory into myfiles.tar.gz.
tar -czvf myfiles.tar.gz myfiles
It’s really that simple. I’ve compressed directories with over 20 gigs of data and I end up being amazed at how fast a tar.gz compression takes.
How to Extract a Compressed Tar.gz file
Once you finish compressing a file, you’ll need to extract the contents of it – either in a local environment or on another server. Below is the command to run when you want to extract the contents of a tarball.
tar -xzvf archive.tar.gz