Compress and extract files using tar command

The GNU tar command included with MacOS and Linux distributions has integrated compression capability. This command has a large number of options but only few are necessary to compress and extract files.

Compress a file or directory

Use the following command to compress an entire directory or a single file

tar -czvf archive_name_here.tar.gz /path/to/directory-or-file

Here is what each option means:

  • -c: create an archive
  • -z: compress the archive with gzip
  • -v: display progress in the terminal also known as verbose mode
  • -f: allow to specify a filename to the archive

Extract an archive

Once you have an archive, you can extract it to the current directory with the following command

tar -xzvf archive_name_here.tar.gz

Here is what each option means:

  • -x: extract an archive
  • -x: use gzip to uncompress the archive
  • -v: display progress in the terminal
  • -f: specify the archive name

By default, everything will be extracted in the current directory. To extract into an arbitrary directory, use the -d option.

tar -xzvf archive_name_here.tar.gz -d /path/to/extract