Tar File(s) or Directories Using the Command Line

Apr 3, 2020 min read

There are many reasons why we might need to Tar files and directories, we might need to upload or download file to and from a server or application, archive files for later retrieval, whatever the reason here are a few helpful commands to get started.

“Taring” is simply a concept where we create a tarball of files and/or directories that are compressed and easier to manipulate and move within a system. Linux (most distros) and Mac have tar commands built into the operating system.

In the terminal a simple tar command might look like:

tar -czvf myphotos.tar.gz /path/to/photos

The above command will compress all files/ directories at the supplied path /path/to/photos into a single file with the given filename, myphotos.tar.gz.

Following the tar command we can pass a series of flags that tell the tar process how to compress the files and what information should be returned. Here is a breakdown of some of the more popular flags:

Flag : : Description
-c Create a tar file (.tar.gz)
-z Compression format, this will use .gzip (more common)
-j Compression format, this will use .bz2
-v Verbose output, helpful for understanding and troubleshooting
-f File to archive to
-x Extract files from a tarball

Examples:

Tar a single file

tar -czvf myphoto.tar.gz /path/to/special-photos/myphoto.png

Tar a directory of files

tar -czvf myphotos.tar.gz /path/to/photos

Tar multiple files/directories

tar -czvf myphotos.tar.gz /path/to/photos /another/path/to/photos /more/photos /path/to/special-photos/myphoto.png

Excluding files/directories

tar -czvf myphotos.tar.gz /path/to/photos --exclude="vacation"

View files in a tar file

This will list the files/directories contained within the tar file.

tar -ztvf myphotos.tar.gz

Extract files

tar -xzvf myphotos.tar.gz

Use the -C flag to extract files to a specific directory.

tar -xzvf myphotos.tar.gz -C ~/Desktop/

I found this article particularly useful.