Skip to content
Laviyx Learn

Try

Linux and Bash course menu

Linux tar and gzip Tutorial: Compress and Extract Files

Create and extract .tar.gz archives with tar, list their contents, exclude files, compress with gzip, and use zip and unzip.

Intermediate6 min readUpdated
On this page

tar bundles many files into one archive, and gzip compresses it. Together they make the .tar.gz files you see everywhere on Linux.

Create an archive#

Terminal
tar -czf project.tar.gz project
ls -lh project.tar.gz | awk '{print $5, $NF}'
du -sh project
Output
108K project.tar.gz
312K	project

Remember the options as "create a zipped file":

OptionMeaning
cCreate
xExtract
tList
zUse gzip
fThe next word is the archive's file name
vVerbose: print each file

List the contents#

Check what is inside before extracting:

Terminal
tar -tzf project.tar.gz
Output
project/
project/node_modules/
project/node_modules/lib.js
project/logs/
project/logs/app.log
project/README.md
project/src/
project/src/app.js

Extract#

Terminal
mkdir restore
tar -xzf project.tar.gz -C restore
ls restore/project
Output
README.md
logs
node_modules
src

-C chooses the destination. Without it, files are extracted into the current folder.

Exclude files#

Leave out dependencies and logs:

Terminal
tar -czf clean.tar.gz --exclude='node_modules' --exclude='*.log' project
tar -tzf clean.tar.gz
Output
project/
project/logs/
project/README.md
project/src/
project/src/app.js

Extract one file#

Terminal
tar -xzf project.tar.gz -O project/README.md
Output
# Project

-O prints to the screen, instead of writing a file.

gzip on its own#

gzip compresses a single file, and replaces it. gunzip reverses that:

Terminal
seq 1 20000 > numbers.txt
ls -l numbers.txt | awk '{print $5}'
gzip numbers.txt
ls -l numbers.txt.gz | awk '{print $5}'
gunzip numbers.txt.gz
ls numbers.txt
Output
108894
45016
numbers.txt

gzip -k keeps the original. zcat and zgrep read compressed files without extracting them, which is useful for old logs:

Terminal
gzip -k numbers.txt
zcat numbers.txt.gz | tail -n 1
zgrep -c 999 numbers.txt.gz
Output
20000
38

zip#

Use zip to share files with Windows users:

Terminal
zip -qr project.zip project/src
unzip -l project.zip | tail -n 1
unzip -qo project.zip -d unzipped
ls unzipped/project/src
Output
       18                     2 files
app.js

Compression compared#

ToolExtensionNotes
gzip.gzFast and available everywhere
bzip2.bz2Smaller, slower
xz.xzMuch smaller, slower
zstd.zstFast and small; widely used now

With tar, change z to j for bzip2, or to J for xz. Already-compressed files such as JPEGs and videos will not shrink much further.

Common mistakes#

Practice#

Practice exercise

Create site.tar.gz from the site folder, leaving out .env, then list the archive.

Show solution
Terminal
tar -czf site.tar.gz --exclude='.env' site
tar -tzf site.tar.gz
Output
site/
site/index.html

Key takeaway#

Next: Network Commands.

Finished this lesson?