tar, gzip and zip on Linux: Create, List and Extract Archives Safely

tar gzip linux - custom-tar-featured.png

Archiving is how you move a directory tree, ship logs to support, or snapshot config before a change. tar bundles files;
gzip compresses the bundle; zip is what Windows colleagues can open without extra tools.

For scheduled off-site backups, see rsync backups or
restic; tar is still the right tool for one-off bundles and vendor tarballs.

Archive vs Compress

tar creates an archive (one file, many members). -z runs gzip on the archive. zip combines both steps in a Windows-friendly format.

bashcommon extensions
ls -lh backup-*.tar.gz site.zip
tar vs zip
Bundle then compress

Create a .tar.gz

Use -c create, -z gzip, -v verbose, -f file name. The -C flag changes directory first so paths stay clean.

basharchive a directory
tar -czvf /backup/etc-$(date +%F).tar.gz -C / etc/nginx etc/ssl
tar -czvf
Create archive

List Before You Extract

Never extract untrusted archives as root without looking. -t lists members; check for absolute paths or ../ tricks.

bashsafe workflow
tar -tzf bundle.tar.gz | head
tar -xzf bundle.tar.gz -C /tmp/restore-test
WarningTarballs from the internet should be extracted as a normal user into an empty directory first.
List and extract
-tzf then -xzf

Exclude Noise

Skip caches, node_modules, and VCS metadata to keep archives small and restores fast.

bashsmaller backup
tar -czvf site.tgz --exclude='*.log' --exclude='node_modules' -C /var/www mysite
Excludes
–exclude

zip and unzip

Handy when recipients are on Windows. unzip -l lists without extracting.

bashzip tree
zip -r docs.zip project/docs/
unzip -l docs.zip | head
zip -r
zip and unzip

Permissions and Ownership

Extracting as root preserves owners from the archive. For untrusted input, use --no-same-owner or extract as your user.

bashextract as user
mkdir -p ~/restore && tar -xzf bundle.tar.gz -C ~/restore
Ownership
root extract risks

Backup Habit: Name, Test, Move

Timestamp archives, verify listing, and periodically restore into /tmp. Copy off-site with rsync or object storage.

bashchecksum
sha256sum /backup/etc-*.tar.gz > /backup/sha256sum.txt
Backup pattern
Test restore

Quick Reference

  • tar -tzf before tar -xzf on unknown files
  • tar -czvf create; zip -r for Windows users
  • Test restores, not just archives

Related tutorials

Diagrams are original illustrations by Gnome IT Solutions. Tutorial text © Gnome IT Solutions.