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.gzorgzip -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.txtOutput
example.txt.gz
example.txt
This is a test file.
Common Pitfalls
Common mistakes when using gzip include:
- Expecting
gzipto compress directories directly (it only compresses files). - Not realizing
gzipdeletes the original file by default after compression. - Trying to decompress files without the
.gzextension.
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
| Option | Description |
|---|---|
| -d | Decompress the file |
| -k | Keep original file after compression or decompression |
| -v | Verbose output showing details |
| -c | Write output to standard output, keep original file |
| -r | Recursively 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.