gzip Command

The gzip command is a popular utility in Linux for compressing and decompressing files. It uses the Lempel-Ziv coding (LZ77) algorithm, which is efficient for reducing the size of various file types, especially text files.

Syntax

gzip [OPTION]... [FILE]...

Description

When you use gzip on a file, it replaces the original file with a compressed version, typically with a .gz extension. To restore the original file, you use the gunzip command or gzip -d. gzip is often used in conjunction with tar to create compressed archives of entire directories.

Common uses include:

  • Compressing single files to save disk space
  • Decompressing .gz files
  • Creating compressed archives (often with tar)
  • Piping output from other commands for compression

Common Options

Option Description
-d, --decompress Decompress. Equivalent to gunzip.
-f, --force Force compression or decompression even if the file has multiple links or the corresponding file already exists.
-k, --keep Keep (don't delete) input files during compression or decompression.
-r, --recursive Recursively compress or decompress files in directories.
-v, --verbose Display name and percentage reduction for each file compressed or decompressed.
-c, --stdout Write output on standard output; keep original files unchanged.
-숫자 Compression level (1-9, 1 is fastest, 9 is best compression). Default is 6.

Examples

Compress a file

gzip myfile.txt
# Result: myfile.txt.gz (original file is deleted)

Compresses myfile.txt and replaces it with myfile.txt.gz.

Decompress a file

gzip -d myfile.txt.gz
# Result: myfile.txt (original .gz file is deleted)

Decompresses myfile.txt.gz and restores myfile.txt.

Compress and keep original file

gzip -k anotherfile.log
# Result: anotherfile.log and anotherfile.log.gz both exist

Compresses anotherfile.log but keeps the original file.

Compress with best compression ratio

gzip -9 largefile.data

Compresses largefile.data using the highest compression level.

Compress a directory (using tar and pipe)

tar -czvf archive.tar.gz mydirectory/

Creates a gzipped tar archive of mydirectory/. (Note: -z option in tar handles gzip).

See also