Linux tar Command: Archive Files

tar bundles files and folders into a single archive file, usually compressed, ending in .tar.gz. It is the standard way to back up folders and move them between Linux computers.

Creating an archive

tar -czvf backup.tar.gz documents/
Creates a compressed archive called backup.tar.gz containing the documents folder.
tar -czvf site.tar.gz --exclude="*.log" website/
Archives the website folder but leaves out any .log files.
tar -cJvf backup.tar.xz documents/
Uses xz compression (-J) instead of gzip. Slower, but the file is smaller.

Looking inside and extracting

tar -tzvf backup.tar.gz
Lists the files in the archive without extracting them.
tar -xzvf backup.tar.gz
Extracts everything into the current directory.
tar -xzvf backup.tar.gz -C restore/
Extracts into the restore directory instead. The directory must already exist.
tar -xzvf backup.tar.gz documents/report.txt
Extracts just one file.
tar -xf backup.tar.xz
Extracts any type of tar archive. Modern tar works out the compression for you.

Check before extracting. Extracting replaces files with the same names. List the contents first with -t if you're not sure.

Zip files

For sharing with Windows users, zip files are often easier. You may need to install the zip and unzip packages first.

zip -r documents.zip documents/
Creates documents.zip from the documents folder.
unzip -l documents.zip
Lists the files in a zip file.
unzip documents.zip -d unzipped/
Extracts a zip file into the unzipped directory.

Quick reference

OptionMeaning
-cCreate an archive
-xExtract
-tList the contents
-zgzip compression (.tar.gz)
-Jxz compression (.tar.xz)
-vShow each file as it is processed
-fThe archive file name (always last)
-C dirExtract into another directory