Compress Extract files using tar command

The command "tar" on Linux or Mac OS terminal is used to compress the folder into a tar/archive file. This page helps in the basic usage and explains how to compress extract files using tar command. The description from the man page says - 

tar creates and manipulates streaming archive files.  This implementation can extract from tar, pax, cpio, zip, jar, ar, xar, rpm, 7-zip, and ISO 9660 cdrom images and can create tar, pax, cpio, ar, zip, 7-zip, and shar archives.

Compress Extract files using tar command

It provides too many options but if you're looking for a quick compression of your files, you can simply enter -

tar -czvf filename.tar.gz /path/of/the/file-or-directory
  • -c is for "creating" a new archive containing the specified items.
  • -z is for compressing the archive with "gzip"
  • -v stands for "verbose". If the folder contains too many items, probably skip this if you dont want to fill the screen with the list of messages. 
  • -f is for specifying the "filename" or location of archive, eg ~/filename.tar.gz.

Eg: I'm in a "mainfolder" and the list of files are as follows

compress extract files using tar command

The 2 immediate child files are "file1.txt" & "file2.txt" with a direcory having another subdirectory in it.

From terminal, the tar file creation would be as follows -

$ tar -czvf main.tar.gz mainfolder/
a mainfolder
a mainfolder/file2.txt
a mainfolder/file1.txt
a mainfolder/directory
a mainfolder/directory/subdir
a mainfolder/directory/subdir/childfile1.txt

The above creates the file "main.tar.gz" in my current directory.

Exclude specific directories or files from the tar file

To ignore few files from the creation of the archive, simply add the folder/file name to the --exclude option.

$ tar --exclude=mainfolder/directory -czvf main.tar.gz mainfolder                                               
a mainfolder
a mainfolder/file2.txt
a mainfolder/file1.txt

Note: The --exclude has to be specified before the -f option. Either way, you can also write -

$ tar czv --exclude mainfolder/directory -f main.tar.gz mainfolder
a mainfolder
a mainfolder/file2.txt
a mainfolder/file1.txt

--exclude also supports the usage of regex in it. So you can also try using eg --exclude=*.DS_Store or --exclude=*.mp4 files from the directory.

Extract an Archive

The most simple way to extract an archived tar file is to use -

tar -xzvf main.tar.gz

As mentioned above, ignore -v if the tar file is too large and you want a clean extraction of the archive on the terminal.