How to Compress Files and Folders in Mac/Linux using Command Line

There are several options to compress files and folders in Mac/Linux. some are these:

1. Compress using ZIP technique:

ZIP one of the most commonly used compression techniques used across all platforms

Zip archives can also be created from the command line by using the terminal command ‘zip’ with the following syntax:

To compress a file: This adds the file file to the archive

zip file

To compress a folder:

zip -r folder_to_compress

you’ll want to skip including those pesky .DS_Store files, for example compressing the whole folder folder into

zip -vr folder/ -x "*.DS_Store"

2. Compress using tar technique:

To tar  a folder, the syntax is:

tar -czf name_of_archive_file.tar name_of_directory_to_tar
  • c – Creates a new .tar archive file.
  • v – Verbosely show the .tar file progress.
  • f – File name type of the archive file.

3. Compress using tar.gz technique:

Tar is the archive tool and gzip is the compression tool. In order to compress a full directory, first you need to archive it to a single file. That’s what the job is tar. and then you compress the archived file. You can do both task in a single tar command with the proper option.

To  gzip a folder, the syntax is:
tar -czf name_of_archive_file.tar.gz name_of_directory_to_tar

It’s worth mentioning what the options -czf after tar are for:

 c indicates that you want to create a tar archive,

 z applies gzip on the intermediate tar archive, and

f is for the subsequent final file name name_of_archive_file.tar.gz

4. Compress using TAR.BZ2 technique:

The bz2 feature compresses and creates archive file less than the size of the gzip.  A variation on tar.gz but with better compression than both tar.gz and zip.

$ tar -cvjf name_of_archive_file.tgz2 name_of_directory_to_tar
$ tar -cvjf name_of_archive_file.tar.bz2 name_of_directory_to_tar

Here, -j option will create a Bzip2 based tar archive & the resulting output file extension will be ‘tgz2’ or ‘tar.bz2