Compressing and extracting files is a routine task on any VPS — for backups, transfers, or freeing up disk space. This guide covers the standard Linux tools and when to use each.
tar: The Standard Linux Archiving Tool
# Create a compressed archive
tar -czvf archive.tar.gz /path/to/directory
# Extract an archive
tar -xzvf archive.tar.gz
# List contents without extracting
tar -tzvf archive.tar.gz
Flags: c=create, x=extract, z=gzip compression, v=verbose, f=specify filename.
Extracting to a Specific Directory
tar -xzvf archive.tar.gz -C /path/to/destination
Using Better Compression with tar (xz/bzip2)
tar -cJvf archive.tar.xz /path/to/directory # xz, better compression, slower
tar -cjvf archive.tar.bz2 /path/to/directory # bzip2, middle ground
xz generally achieves better compression ratios than gzip at the cost of more CPU time and slower compression/extraction — a worthwhile trade for archival storage, less so for frequent operations.
gzip: Compressing Single Files
gzip largefile.log
gunzip largefile.log.gz
Unlike tar, gzip compresses a single file in place, replacing the original — use tar first if you need to bundle multiple files/directories before compressing.
zip/unzip: Cross-Platform Compatibility
sudo apt install zip unzip -y
zip -r archive.zip /path/to/directory
unzip archive.zip
Useful specifically when the archive needs to be opened easily on Windows, since ZIP has broader native OS support than tar.gz there.
Excluding Files/Directories from an Archive
tar -czvf archive.tar.gz --exclude='node_modules' --exclude='*.log' /path/to/directory
Checking Archive Size Before Extracting
tar -tzvf archive.tar.gz | awk '{sum += $3} END {print sum}'
Useful before extracting a large, unfamiliar archive to confirm sufficient disk space is available.
Splitting Large Archives into Smaller Parts
tar -czvf - /path/to/directory | split -b 1G - archive-part-
cat archive-part-* | tar -xzvf -
Useful when transferring very large archives through systems with file size limits.
Choosing the Right Format
| Format | Best For |
|---|---|
| tar.gz | General purpose, good balance of speed and compression, the Linux default |
| tar.xz | Best compression ratio, when archive size matters more than speed |
| zip | Cross-platform sharing, especially with Windows users |
Common Errors
"tar: Cannot open: No such file or directory" — verify the path to the source file/directory is correct and exists.
Extraction fills the disk unexpectedly — check the archive's uncompressed size first (see above) before extracting an unfamiliar large archive.
Continue Reading
- How to Check and Manage Disk Usage on a Linux VPS
- How to Transfer Files To and From a VPS (SCP, SFTP & rsync)
- How to Set Up Automated VPS Backups
Browse more articles in Linux Server Administration.