0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use gzip Command in Linux: Syntax and Examples

Use the gzip command in Linux to compress files by running gzip filename. To decompress, use gunzip filename.gz or gzip -d filename.gz.
📐

Syntax

The basic syntax of the gzip command is:

  • gzip [options] filename - Compress the specified file.
  • gunzip [options] filename.gz or gzip -d [options] filename.gz - Decompress the specified gzip file.

Common options include:

  • -d: Decompress the file.
  • -k: Keep the original file after compression or decompression.
  • -v: Verbose mode, shows details of the operation.
bash
gzip [options] filename

gunzip [options] filename.gz

gzip -d [options] filename.gz
💻

Example

This example compresses a file named example.txt and then decompresses it back.

bash
echo "This is a test file." > example.txt
gzip example.txt
ls example.txt.gz

gzip -d example.txt.gz
ls example.txt
cat example.txt
Output
example.txt.gz example.txt This is a test file.
⚠️

Common Pitfalls

Common mistakes when using gzip include:

  • Expecting gzip to compress directories directly (it only compresses files).
  • Not realizing gzip deletes the original file by default after compression.
  • Trying to decompress files without the .gz extension.

To avoid losing original files, use the -k option.

bash
gzip example.txt  # Compresses and deletes original file

# Better to keep original:
gzip -k example.txt  # Compresses and keeps original file
📊

Quick Reference

OptionDescription
-dDecompress the file
-kKeep original file after compression or decompression
-vVerbose output showing details
-cWrite output to standard output, keep original file
-rRecursively compress files in directories (use with caution)

Key Takeaways

Use gzip filename to compress and gunzip filename.gz or gzip -d filename.gz to decompress files.
By default, gzip deletes the original file after compression; use -k to keep it.
gzip compresses only files, not directories directly; use tar with gzip for directories.
Use -v option to see detailed output of compression or decompression.
Always check file extensions to avoid decompressing wrong files.