logo hsb.horse
← Back to snippets index

Snippets

gzip Command Cheat Sheet

A snippet covering the basic usage of the gzip command, including file compression, decompression, and option flags.

Published: Updated:

Basic Compression

Terminal window
gzip "path/to/file"

After compression, the original file is removed and file.gz is created.

Compress While Keeping the Original File

Terminal window
gzip -k "path/to/file"

Compress a Directory Recursively

Terminal window
gzip -r "path/to/dir"

Each file inside the directory is compressed individually into .gz files.

Decompress

Terminal window
gzip -d "path/to/file.gz"
# or
gunzip "path/to/file.gz"

gunzip is an alias for gzip -d.

Decompress to a Different File

Terminal window
gzip -cd "path/to/file.gz" > "path/to/file"

-c outputs to stdout, and the redirect specifies the destination.

Specify Compression Level

Terminal window
gzip -1 "path/to/file" # Fastest, lowest compression
gzip -9 "path/to/file" # Best compression, slowest
LevelAliasCharacteristics
-1--fastFast, lower compression ratio
-6(default)Balanced speed and compression ratio
-9--bestSlow, higher compression ratio

Show Information About a Compressed File

Terminal window
gzip -l "path/to/file.gz"

Displays the original size, compressed size, compression ratio, and filename.

Integrity Check

Terminal window
gzip -t "path/to/file.gz"

No output means the file is valid. If corrupted, an error such as gzip: path/to/file.gz: invalid compressed data--crc error will appear.

Archive and Compress a Directory with tar

Terminal window
# Compress
tar cf - "path/to/dir" | gzip > archive.tar.gz
# or
tar czf archive.tar.gz "path/to/dir"
# Extract
tar xzf archive.tar.gz

Unlike the -r option, this bundles the entire directory structure into a single file.

Comparison with Other Tools

ToolExtensionDescription
gzip.gzFast, widely supported, standard choice
bzip2.bz2Higher compression than gzip, but slower
xz.xzBest compression ratio, but heavy processing
zstd.zstFast and high compression. Suited for modern use