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.
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#
tar -czf project.tar.gz project
ls -lh project.tar.gz | awk '{print $5, $NF}'
du -sh project108K project.tar.gz
312K projectRemember the options as "create a zipped file":
List the contents#
Check what is inside before extracting:
tar -tzf project.tar.gzproject/
project/node_modules/
project/node_modules/lib.js
project/logs/
project/logs/app.log
project/README.md
project/src/
project/src/app.jsExtract#
mkdir restore
tar -xzf project.tar.gz -C restore
ls restore/projectREADME.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:
tar -czf clean.tar.gz --exclude='node_modules' --exclude='*.log' project
tar -tzf clean.tar.gzproject/
project/logs/
project/README.md
project/src/
project/src/app.jsExtract one file#
tar -xzf project.tar.gz -O project/README.md# 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:
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.txt108894
45016
numbers.txtgzip -k keeps the original. zcat and zgrep read compressed files without extracting them, which is useful for old logs:
gzip -k numbers.txt
zcat numbers.txt.gz | tail -n 1
zgrep -c 999 numbers.txt.gz20000
38zip#
Use zip to share files with Windows users:
zip -qr project.zip project/src
unzip -l project.zip | tail -n 1
unzip -qo project.zip -d unzipped
ls unzipped/project/src 18 2 files
app.jsCompression compared#
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
tar -czf site.tar.gz --exclude='.env' site
tar -tzf site.tar.gzsite/
site/index.htmlKey takeaway#
Next: Network Commands.
Finished this lesson?