|

Linux CLI 38 🐧 gzip and bzip2 commands

gzip file.txt
gzip -d file.txt
gzip -v file.txt file1.txt

bzip2 -k 1.txt
bzip2 -d 1.txt.bz2 
bzip2 -d -f 1.txt.bz2 
bzip2 -k 1.txt 2.txt

gzip and bzip2 are the two classic compression tools on Linux. They both shrink files to save disk space and make transfers faster, and they both work on single files — not directories. The difference is in the trade-off: gzip is fast and widely supported; bzip2 compresses better but is slower.

Key point: Both tools delete the original file by default. Use -k (--keep) to preserve it. Neither can compress a directory directly — you need tar for that, or combine with find.


a – gzip command

gzip is used to compress and decompress files. File compression helps save disk space and transfer files faster. It’s the default compression format on most Linux systems and is recognized almost everywhere.

Important: gzip cannot compress a folder. To compress a directory, you either combine it with find or use tar to bundle it first.

CommandDescription
gzip file.txtCompresses one file → file.txt.gz
gzip -d file.txt.gzDecompresses one file
gzip -v file.txt file1.txtCompresses multiple files with verbose output
gzip -k file.txtCompresses and keeps the original
gzip -l file.txt.gzLists compression info
gzip -r DIRRecursively compress files in a directory

How to compress a folder:

# Option 1: find each file and gzip it
find /directory/to/compress -type f -exec gzip {} \;

# Option 2: tar + gzip (the classic combo)
tar -czvf archive.tar.gz /directory/to/compress

# Option 3: pipe a listing through gzip
ls -l /directory/to/compress | gzip > foo.txt.gz

Examples:

# Compress one file
$ gzip file.txt
$ ls -l
-rw-r--r-- 1 kronos kronos 512 Jan 15 10:00 file.txt.gz
# Note: file.txt is gone!

# Decompress
$ gzip -d file.txt.gz
$ ls -l
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 file.txt

# Keep the original
$ gzip -k file.txt
$ ls -l
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 file.txt
-rw-r--r-- 1 kronos kronos  512 Jan 15 10:00 file.txt.gz

# Compress multiple files (verbose)
$ gzip -v file.txt file1.txt
file.txt:    50.0% -- replaced with file.txt.gz
file1.txt:   42.3% -- replaced with file1.txt.gz

# List info about a gzip file
$ gzip -l file.txt.gz
         compressed        uncompressed  ratio uncompressed_name
                512                1024  50.0% file.txt

# Test integrity without decompressing
$ gzip -t file.txt.gz

# Recursively compress all files in a directory
$ gzip -r mydir/
$ ls mydir/
file1.txt.gz  file2.txt.gz  subdir/

# Compress from stdin (no file needed)
$ cat file.txt | gzip > file.txt.gz

# Decompress to stdout without creating a file
$ gzip -dc file.txt.gz
hello world
...

Reading the verbose output:

FieldMeaning
file.txtOriginal filename
50.0%How much smaller the file got
replaced with file.txt.gzOriginal was deleted, new file created

Useful options:

OptionPurpose
-dDecompress
-kKeep the original file
-vVerbose
-lList compression info
-rRecursive
-cWrite to stdout
-tTest integrity
-fForce (overwrite, compress links)
-1-9Compression level (1=fastest, 9=best)
-9Best compression (default is 6)

Compression levels:

# Fastest, least compression
$ gzip -1 file.txt

# Default
$ gzip file.txt

# Best compression, slowest
$ gzip -9 file.txt

Tip: For text files, gzip typically gets 60–80% reduction. For already-compressed files (.jpg, .mp4, .zip), you’ll see almost no gain — and might even make them bigger.


b – bzip2 command

bzip2 is used to compress and decompress files. Like gzip, bzip2 deletes the original file by default — use -k to keep it. The .bz2 extension shows that a file has been compressed with bzip2.

bzip2 vs gzip:

Aspectgzipbzip2
SpeedFastSlower
CompressionGoodBetter (~10–15% smaller)
Memory useLowHigher
Extension.gz.bz2
UbiquityEverywhereCommon but less universal

Use bzip2 when: You want the smallest possible file and don’t mind waiting.
Use gzip when: You want speed and universal compatibility.

CommandDescription
bzip2 -k 1.txtCompresses a file and keeps the original
bzip2 -d 1.txt.bz2Decompresses a file
bzip2 -d -f 1.txt.bz2Decompresses and overwrites
bzip2 -k 1.txt 2.txtCompresses multiple files into multiple .bz2 files
bzmore 1.txt.bz2Shows the contents of a compressed file

Examples:

# Compress a file and keep the original
$ bzip2 -k 1.txt
$ ls -l
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 1.txt
-rw-r--r-- 1 kronos kronos  400 Jan 15 10:00 1.txt.bz2

# Decompress a file
$ bzip2 -d 1.txt.bz2
$ ls -l
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 1.txt

# Decompress and overwrite existing file
$ bzip2 -d -f 1.txt.bz2
# -f forces overwrite if 1.txt already exists

# Compress multiple files
$ bzip2 -k 1.txt 2.txt
$ ls -l
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 1.txt
-rw-r--r-- 1 kronos kronos  400 Jan 15 10:00 1.txt.bz2
-rw-r--r-- 1 kronos kronos 2048 Jan 15 10:00 2.txt
-rw-r--r-- 1 kronos kronos  800 Jan 15 10:00 2.txt.bz2

# View a compressed file without decompressing
$ bzmore 1.txt.bz2
------> 1.txt.bz2 <------
hello world
this is the content
...
(END)

# Verbose mode
$ bzip2 -v -k 1.txt
  1.txt:  2.500:1,  3.200 bits/byte, 60.00% saved, 1024 in, 400 out.

# Test integrity
$ bzip2 -t 1.txt.bz2

# Compress to stdout
$ bzip2 -c 1.txt > 1.txt.bz2

# Decompress to stdout
$ bzcat 1.txt.bz2
hello world
...

Useful options:

OptionPurpose
-dDecompress
-kKeep the original file
-fForce (overwrite existing)
-vVerbose
-tTest integrity
-cWrite to stdout
-1-9Compression level
-zCompress (default)

Related bzip2 tools:

ToolPurpose
bunzip2Same as bzip2 -d
bzcatDecompress to stdout
bzmorePage through a compressed file
bzlessLike bzmore with search
bzgrepSearch inside a compressed file

Examples with related tools:

# bunzip2 = bzip2 -d
$ bunzip2 1.txt.bz2

# bzcat = decompress to stdout
$ bzcat 1.txt.bz2
hello world
...

# bzgrep = grep inside a compressed file
$ bzgrep "error" log.txt.bz2
2024-01-15 10:30:00 error: connection refused
2024-01-15 10:35:00 error: timeout

# bzless = searchable pager
$ bzless 1.txt.bz2

Tip: The same family exists for gzip: gunzip, zcat, zless, zgrep, zdiff. They’re all convenience wrappers.


Complete Example Session

# ============================================
# PART 1: GZIP BASICS
# ============================================

# Compress a single file
$ ls -l file.txt
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 file.txt

$ gzip file.txt
$ ls -l file.txt.gz
-rw-r--r-- 1 kronos kronos 512 Jan 15 10:00 file.txt.gz
# ✅ file.txt is now file.txt.gz (original removed)

# Decompress
$ gzip -d file.txt.gz
$ ls -l file.txt
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 file.txt

# Keep the original
$ gzip -k file.txt
$ ls -l file.txt file.txt.gz
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 file.txt
-rw-r--r-- 1 kronos kronos  512 Jan 15 10:00 file.txt.gz

# Compress multiple files verbosely
$ gzip -v file.txt file1.txt
file.txt:    50.0% -- replaced with file.txt.gz
file1.txt:   42.3% -- replaced with file1.txt.gz

# List info
$ gzip -l file.txt.gz
         compressed        uncompressed  ratio uncompressed_name
                512                1024  50.0% file.txt

# ============================================
# PART 2: GZIP ON A DIRECTORY
# ============================================

# gzip can't compress a folder directly
$ gzip myfolder/
gzip: myfolder/ is a directory -- ignored

# Option 1: compress each file
$ find myfolder -type f -exec gzip {} \;
$ ls myfolder/
file1.txt.gz  file2.txt.gz  file3.txt.gz

# Option 2: tar + gzip
$ tar -czvf myfolder.tar.gz myfolder/
myfolder/
myfolder/file1.txt
myfolder/file2.txt
myfolder/file3.txt

# ============================================
# PART 3: GZIP LEVELS
# ============================================

$ gzip -1 file.txt         # fastest
$ gzip -9 file.txt         # best compression
$ gzip file.txt            # default (6)

# ============================================
# PART 4: BZIP2 BASICS
# ============================================

# Compress and keep the original
$ bzip2 -k 1.txt
$ ls -l 1.txt 1.txt.bz2
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 1.txt
-rw-r--r-- 1 kronos kronos  400 Jan 15 10:00 1.txt.bz2

# Decompress
$ bzip2 -d 1.txt.bz2
$ ls -l 1.txt
-rw-r--r-- 1 kronos kronos 1024 Jan 15 10:00 1.txt

# Decompress with force
$ bzip2 -d -f 1.txt.bz2

# Compress multiple files
$ bzip2 -k 1.txt 2.txt
$ ls -l 1.txt.bz2 2.txt.bz2
-rw-r--r-- 1 kronos kronos  400 Jan 15 10:00 1.txt.bz2
-rw-r--r-- 1 kronos kronos  800 Jan 15 10:00 2.txt.bz2

# ============================================
# PART 5: BZIP2 VIEWING TOOLS
# ============================================

# View compressed file
$ bzmore 1.txt.bz2
------> 1.txt.bz2 <------
hello world
(END)

# Cat to stdout
$ bzcat 1.txt.bz2
hello world

# Search inside
$ bzgrep "hello" 1.txt.bz2
hello world

# ============================================
# PART 6: COMPARE SIZES
# ============================================

$ ls -l original.txt
-rw-r--r-- 1 kronos kronos 10240 Jan 15 10:00 original.txt

$ gzip -k original.txt
$ ls -l original.txt.gz
-rw-r--r-- 1 kronos kronos 4000 Jan 15 10:00 original.txt.gz

$ bzip2 -k original.txt
$ ls -l original.txt.bz2
-rw-r--r-- 1 kronos kronos 3400 Jan 15 10:00 original.txt.bz2

# bzip2 typically beats gzip by ~10-15%

Quick Reference

gzip

CommandPurpose
gzip FILECompress a file
gzip -d FILE.gzDecompress
gzip -k FILEKeep the original
gzip -v FILEVerbose
gzip -l FILE.gzList info
gzip -r DIRRecursive
gzip -t FILE.gzTest integrity
gzip -c FILE > out.gzTo stdout
gzip -1-9Compression levels

bzip2

CommandPurpose
bzip2 FILECompress a file
bzip2 -d FILE.bz2Decompress
bzip2 -k FILEKeep the original
bzip2 -d -f FILE.bz2Decompress + overwrite
bzip2 -v FILEVerbose
bzip2 -t FILE.bz2Test integrity
bzip2 -1-9Compression levels

Related Tools

ToolPurpose
gunzipSame as gzip -d
zcatDecompress to stdout
zless / zmorePage through .gz
zgrepSearch inside .gz
bunzip2Same as bzip2 -d
bzcatDecompress to stdout
bzless / bzmorePage through .bz2
bzgrepSearch inside .bz2

gzip vs bzip2

Aspectgzipbzip2
Extension.gz.bz2
SpeedFastSlower
CompressionGoodBetter
MemoryLowHigher
CompatibilityUniversalCommon
Best forGeneral useMaximum compression

Best Practices

Do This:

# Use -k to keep the original
gzip -k file.txt                       # ✅
bzip2 -k file.txt                      # ✅

# Use tar for directories
tar -czvf dir.tar.gz dir/              # ✅

# Use -9 for maximum compression
gzip -9 file.txt                       # ✅

# Test integrity after transfer
gzip -t file.txt.gz                    # ✅
bzip2 -t file.txt.bz2                  # ✅

# Use zcat / bzcat to view without extracting
zcat file.txt.gz                       # ✅
bzcat file.txt.bz2                     # ✅

# Combine with find for directories
find dir -type f -exec gzip {} \;      # ✅

Don’t Do This:

# Don't gzip without -k if you need the original
gzip important.txt                     # ❌ deletes original

# Don't try to gzip a directory directly
gzip myfolder/                         # ❌ ignored

# Don't use bzip2 on huge files if speed matters
bzip2 -9 hugefile.iso                  # ❌ slow

# Don't compress already-compressed files
gzip photo.jpg                         # ❌ no gain

# Don't forget -f to overwrite on decompress
bzip2 -d 1.txt.bz2                     # ❌ fails if 1.txt exists

# Don't overwrite originals by mistake
gzip -f file.txt                       # ❌ careful with -f

Common Pitfalls

PitfallProblemSolution
Original file deletedSurprise data lossUse -k
Can’t compress a directorygzip refusesUse tar or find
No size reductionAlready compressedDon’t compress .jpg, .mp4
Decompress failsFile existsUse -f to overwrite
Wrong extensionConfusion.gz vs .bz2
Very slowHigh compression levelUse lower -1-9
Corrupted archiveBad transfergzip -t / bzip2 -t
Shell glob breaksSpace in filenameQuote the filename

Real-World Examples

1. Compress a Log File

$ gzip -v /var/log/app.log
/var/log/app.log:  85.3% -- replaced with /var/log/app.log.gz

2. Compress and Keep the Original

$ gzip -k important.txt
$ ls -l important.txt*
-rw-r--r-- 1 kronos kronos 10240 Jan 15 10:00 important.txt
-rw-r--r-- 1 kronos kronos  2000 Jan 15 10:00 important.txt.gz

3. Compress a Whole Directory

$ tar -czvf backup.tar.gz /home/kronos/projects/
tar: Removing leading `/' from member names
/home/kronos/projects/
/home/kronos/projects/file1.txt
/home/kronos/projects/file2.txt
...

4. Compress Every File in a Directory

$ find /var/log -type f -name '*.log' -exec gzip {} \;
$ ls /var/log/*.gz
/var/log/syslog.gz  /var/log/auth.log.gz

5. Decompress and View Without Extracting

$ zcat app.log.gz | grep "ERROR"
2024-01-15 10:30:00 ERROR: connection refused

$ bzcat app.log.bz2 | tail -n 20

6. Search Inside a Compressed Log

$ zgrep "ERROR" /var/log/syslog.gz
2024-01-15 10:30:00 ERROR: connection refused
2024-01-15 10:35:00 ERROR: timeout

7. Decompress a .gz from a Download

$ wget 'https://example.com/data.txt.gz'
$ gunzip data.txt.gz
$ ls -l data.txt
-rw-r--r-- 1 kronos kronos 1048576 Jan 15 10:00 data.txt

8. Compare gzip and bzip2 Sizes

$ cp bigfile.txt bigfile_gzip.txt
$ cp bigfile.txt bigfile_bzip2.txt

$ gzip bigfile_gzip.txt
$ bzip2 bigfile_bzip2.txt

$ ls -l bigfile.txt bigfile_gzip.txt.gz bigfile_bzip2.txt.bz2
-rw-r--r-- 1 kronos kronos 10240000 Jan 15 10:00 bigfile.txt
-rw-r--r-- 1 kronos kronos  4000000 Jan 15 10:00 bigfile_gzip.txt.gz
-rw-r--r-- 1 kronos kronos  3400000 Jan 15 10:00 bigfile_bzip2.txt.bz2
# bzip2 is ~15% smaller

9. Test an Archive Before Using It

$ gzip -t backup.tar.gz && echo "OK"
OK

$ bzip2 -t backup.tar.bz2 && echo "OK"
OK

10. Stream Compress via a Pipe

$ mysqldump mydb | gzip > mydb.sql.gz
$ tar -cf - mydir/ | bzip2 > mydir.tar.bz2
$ cat access.log | gzip > access.log.gz

11. Compress with Maximum Compression

$ gzip -9 -v archive.txt
archive.txt:  88.0% -- replaced with archive.txt.gz

$ bzip2 -9 -v archive.txt
archive.txt:  89.5% -- replaced with archive.txt.bz2

12. Extract All .gz Files in a Directory

$ gunzip *.gz
$ ls
file1.txt  file2.txt  file3.txt

Visual: How gzip and bzip2 Work

┌──────────────────────────────────────────────┐
│         gzip file.txt                        │
│                                              │
│   file.txt (1024 bytes)                      │
│         │                                    │
│         ▼                                    │
│   ┌─────────────────┐                        │
│   │  gzip compress  │                        │
│   └────────┬────────┘                        │
│            │                                 │
│            ▼                                 │
│   file.txt.gz (512 bytes)                    │
│                                              │
│   Original file is REMOVED                   │
│                                              │
└──────────────────────────────────────────────┘

┌──────────────────────────────────────────────┐
│         gzip -k file.txt                     │
│                                              │
│   file.txt (1024 bytes)                      │
│         │                                    │
│         ├──► file.txt (still there)          │
│         │                                    │
│         ▼                                    │
│   file.txt.gz (512 bytes)                    │
│                                              │
│   Original file is KEPT                      │
│                                              │
└──────────────────────────────────────────────┘

┌──────────────────────────────────────────────┐
│         Directory compression                │
│                                              │
│   mydir/                                     │
│   ├── file1.txt                              │
│   ├── file2.txt                              │
│   └── file3.txt                              │
│                                              │
│   ❌ gzip mydir/  (refuses)                  │
│                                              │
│   ✅ tar -czvf mydir.tar.gz mydir/           │
│   ✅ find mydir -type f -exec gzip {} \;     │
│                                              │
└──────────────────────────────────────────────┘

Summary

CommandPurposeExample
gzip FILECompress (deletes original)gzip file.txt
gzip -k FILECompress + keep originalgzip -k file.txt
gzip -d FILE.gzDecompressgzip -d file.txt.gz
gzip -v FILEVerbosegzip -v file.txt
gzip -l FILE.gzList infogzip -l file.txt.gz
gzip -t FILE.gzTest integritygzip -t file.txt.gz
gzip -1-9Compression levelgzip -9 file.txt
gzip -r DIRRecursivegzip -r mydir/
bzip2 FILECompress (deletes original)bzip2 1.txt
bzip2 -k FILECompress + keep originalbzip2 -k 1.txt
bzip2 -d FILE.bz2Decompressbzip2 -d 1.txt.bz2
bzip2 -d -f FILE.bz2Decompress + forcebzip2 -d -f 1.txt.bz2
bzip2 -t FILE.bz2Test integritybzip2 -t 1.txt.bz2
bzmore FILE.bz2View compressedbzmore 1.txt.bz2
bzcat FILE.bz2Decompress to stdoutbzcat 1.txt.bz2
bzgrep PAT FILE.bz2Search insidebzgrep error log.bz2
tar -czvf A.tar.gz DIRDirectory with gziptar -czvf a.tar.gz dir/
tar -cjvf A.tar.bz2 DIRDirectory with bzip2tar -cjvf a.tar.bz2 dir/

Key takeaways:

  • gzip and bzip2 compress single files — not directories
  • Both delete the original by default — use -k to keep it
  • gzip is fast and universal; bzip2 compresses ~10–15% smaller but slower
  • Use -d to decompress, -v for verbose, -t to test integrity
  • For directories, use tar -czvf (gzip) or tar -cjvf (bzip2), or find … -exec gzip
  • Use zcat, bzcat, zgrep, bzgrep, zless, bzless to work with compressed files without extracting
  • Compression level -1 is fastest, -9 is best — default is 6
  • Don’t compress already-compressed files (.jpg, .mp4, .zip) — no gain
  • Always test archives after transferring them

Remember: gzip and bzip2 both shrink files, but neither handles directories. Keep originals with -k. Use tar when you need to bundle a directory. Use zcat/bzcat when you want to peek inside without extracting. For a quick, universal format, choose gzip. For the smallest possible file and you’re not in a hurry, choose bzip2. Master both, and your disk — and your transfers — will thank you.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!