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
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
.gzfiles - 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
# Result: myfile.txt.gz (original file is deleted)
Compresses myfile.txt and replaces it with myfile.txt.gz.
Decompress a file
# Result: myfile.txt (original .gz file is deleted)
Decompresses myfile.txt.gz and restores myfile.txt.
Compress and keep original file
# Result: anotherfile.log and anotherfile.log.gz both exist
Compresses anotherfile.log but keeps the original file.
Compress with best compression ratio
Compresses largefile.data using the highest compression level.
Compress a directory (using tar and pipe)
Creates a gzipped tar archive of mydirectory/. (Note: -z option in tar handles gzip).