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.gzLists the files in the archive without extracting them.
tar -xzvf backup.tar.gzExtracts 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.txtExtracts just one file.
tar -xf backup.tar.xzExtracts 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.zipLists the files in a zip file.
unzip documents.zip -d unzipped/Extracts a zip file into the unzipped directory.
Quick reference
| Option | Meaning |
|---|---|
-c | Create an archive |
-x | Extract |
-t | List the contents |
-z | gzip compression (.tar.gz) |
-J | xz compression (.tar.xz) |
-v | Show each file as it is processed |
-f | The archive file name (always last) |
-C dir | Extract into another directory |