How to Unzip a .gz File in Linux: gunzip, gzip -d, and zcat Guide
Learn unzip a gz file in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn unzip a gz file in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What gzip Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Knowing how to unzip a gz file in linux correctly is a frequent requirement when deploying packages, restoring database snapshots, and analyzing historical log files. While novice users often attempt to run the unzip command on a .gz file—which fails because .gz files use the Gzip single-file container rather than the PKZIP multi-file format—Linux provides dedicated utilities like gunzip, gzip -d, and zcat to extract these archives cleanly.
To unzip a .gz file in Linux, use the gunzip command or gzip -d (e.g. gunzip file.gz or gzip -d file.gz). To keep the original compressed .gz archive, add the -k flag (e.g. gzip -dk file.gz). For .tar.gz archives containing multiple files and folders, extract with tar -xzvf file.tar.gz.
The Gzip decompression ecosystem is designed for maximum pipeline composability. You can extract files directly on disk, decompress in-memory streams from curl or ssh without touching storage, or inspect text files directly using utilities like zgrep, zless, and zcat without expanding them on disk.
Furthermore, understanding the critical difference between standalone .gz files (a single compressed file) and .tar.gz / .tgz files (a multi-file tarball compressed with gzip) ensures you choose the right command toolchain and avoid cluttering your working directory with misplaced archive members.
What gzip Does and When to Use It
Under the hood, decompressing a .gz file involves reversing the DEFLATE algorithm. The decompression engine reads the 10-byte RFC 1952 header, verifies the 0x1F 0x8B magic bytes, and parses Huffman code tree tables. As compressed token streams are processed, the sliding window reconstructs original text and binary data, writing uncompressed bytes to standard output or the destination file descriptor.
Throughout decompression, the kernel streaming pipeline continuously computes a running 32-bit CRC checksum across the emitted uncompressed bytes. Upon reaching the end of the DEFLATE stream, gunzip reads the 8-byte trailer: the first 4 bytes contain the expected CRC-32 checksum, and the last 4 bytes represent the original uncompressed byte length (modulo $2^{32}$). If the calculated CRC does not match the trailer, gunzip reports an integrity error and terminates with an exit status of 1.
Under the hood, gzip gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -d, -k, -c, -f turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The gzip utility is packaged in gzip across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether gzip is installed and inspect which binary path and version your shell resolves:
type -a gzip
gzip --version 2>/dev/null || man -f gzip
# Illustrative output (reviewed against documentation)
gzip is /usr/bin/gzip
gzip (gzip)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y gzip
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y gzip
# Arch Linux
sudo pacman -S --noconfirm gzip
# Alpine Linux
sudo apk add --no-cache gzip
Command Syntax, Arguments, and Exit Status Codes
gzip -d [OPTIONS] FILE.gz | gunzip [OPTIONS] FILE.gz
Linux offers several equivalent syntax forms to unzip a .gz file: gunzip [OPTIONS] FILE.gz, gzip -d [OPTIONS] FILE.gz, or streaming via zcat FILE.gz > OUTPUT. For tarballs, use tar -xzvf FILE.tar.gz.
By default, gunzip and gzip -d remove the .gz suffix and delete the original .gz archive, replacing it with the uncompressed file. To keep both the compressed archive and the extracted file, pass the -k (--keep) flag.
0— Decompression succeeded; CRC-32 checksum verified.1— Decompression failed; invalid format, corrupted data, or CRC mismatch.2— Warning; file skipped or unrecognized file extension.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-d | --decompress | Decompress the target .gz archive (default behavior for gunzip). |
-k | --keep | Keep (do not delete) the input .gz archive after decompression. |
-c | --stdout | Write decompressed output to stdout; leaves original .gz archive untouched. |
-f | --force | Force decompression even if target file already exists or is a hard link. |
-t | --test | Test the integrity of the .gz archive without writing uncompressed output. |
-v | --verbose | Display filename, decompression percentage, and progress information. |
-l | --list | List compressed and uncompressed sizes and ratio without extracting. |
The choice between gunzip file.gz and gzip -dk file.gz comes down to file retention. gunzip file.gz replaces the archive with the uncompressed file. Adding -k (or running gzip -dk) ensures your archive remains intact as a safety backup.
When working with multi-gigabyte files, streaming with zcat file.gz | command or gzip -dc file.gz | command avoids writing massive uncompressed files to disk, preserving storage space and disk I/O bandwidth.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Decompress a .gz File and Replace It
Standard decompression of a .gz file using gunzip, replacing the archive with the original file.
gunzip access.log.gz
ls -l access.log
# Illustrative output (reviewed against documentation)
-rw-r--r-- 1 ubuntu ubuntu 4512010 Oct 22 14:00 access.log
gunzip extracts the original uncompressed file and automatically deletes access.log.gz.
2. Decompress and Keep the Original .gz File with -k
Extract a .gz archive while keeping the compressed file intact for backup purposes.
gzip -dk database.sql.gz
ls -l database.sql*
# Illustrative output (reviewed against documentation)
-rw-r--r-- 1 ubuntu ubuntu 12450120 Oct 22 14:10 database.sql
-rw-r--r-- 1 ubuntu ubuntu 2841020 Oct 22 14:10 database.sql.gz
The -k flag instructs gzip/gunzip to retain database.sql.gz after extracting database.sql.
3. View Contents of a .gz File Without Extracting Using zcat
Output the text content of a compressed file directly to terminal stdout.
zcat /var/log/dpkg.log.1.gz | head -n 3
# Illustrative output (reviewed against documentation)
2026-10-01 06:25:10 startup archives unpack
2026-10-01 06:25:11 upgrade libssl3:amd64 3.0.2-0ubuntu1.10
2026-10-01 06:25:12 status half-configured libssl3:amd64 3.0.2-0ubuntu1.10
zcat decompresses the file on-the-fly directly to standard output without writing anything to disk.
4. Extract a .tar.gz Multi-File Archive Using tar
Extract an archive containing multiple files and nested directories created with tar.
tar -xzvf project_backup.tar.gz -C /opt/app/
# Illustrative output (reviewed against documentation)
project/
project/src/
project/src/index.js
project/package.json
The -x (extract), -z (gzip), and -v (verbose) flags with -C extract the archive into /opt/app/.
5. Search Inside a Compressed File Using zgrep
Search for specific error terms inside a compressed log file without decompressing it first.
zgrep -i "error" /var/log/nginx/error.log.2.gz | head -n 2
# Illustrative output (reviewed against documentation)
2026/10/18 11:14:02 [error] 1104#1104: *401 open() "/var/www/html/404" failed
2026/10/18 11:15:30 [error] 1104#1104: *412 connection timed out
zgrep decompresses the stream in memory and runs grep directly against the decompressed text.
6. Decompress Multiple .gz Files Simultaneously
Batch decompress all rotated log files in a directory.
gzip -dk /var/log/nginx/*.gz
# Illustrative output (reviewed against documentation)
# Decompresses all .gz files in /var/log/nginx while retaining the originals
gzip accepts shell globs and decompresses each matched archive sequentially.
Real-World Workflows, Pipelines, and Shell Automation
Database Restoration Pipeline: Streaming Compressed Dumps into PostgreSQL
Restore a multi-gigabyte compressed database snapshot directly without writing raw SQL to disk.
#!/usr/bin/env bash
set -euo pipefail
DUMP_FILE="/backups/production_db_20261022.sql.gz"
DB_NAME="production_restore"
echo "Verifying archive integrity before restoration..."
gzip -t "$DUMP_FILE"
echo "Streaming decompressed snapshot directly into PostgreSQL database '$DB_NAME'..."
gzip -dc "$DUMP_FILE" | psql -U postgres -d "$DB_NAME"
echo "Database restoration completed successfully."
# Illustrative output (reviewed against documentation)
Verifying archive integrity before restoration...
Streaming decompressed snapshot directly into PostgreSQL database 'production_restore'...
SET
SET
CREATE TABLE
ALTER TABLE
Database restoration completed successfully.
Streaming through gzip -dc pipes uncompressed SQL statements directly to the database client, requiring zero extra disk space.
Security Forensics: Auditing Historical Compressed System Logs
Search through all compressed historical authentication logs for brute-force attacks across past months.
#!/usr/bin/env bash
set -euo pipefail
echo "=== Historical Brute Force Login Tally (Archived Logs) ==="
zgrep -h "Failed password" /var/log/auth.log.*.gz 2>/dev/null \
| awk '{print $(NF-3)}' \
| sort \
| uniq -c \
| sort -nr \
| head -n 5
# Illustrative output (reviewed against documentation)
=== Historical Brute Force Login Tally (Archived Logs) ===
1482 198.51.100.44
912 203.0.113.89
410 192.0.2.112
215 198.51.100.12
120 203.0.113.15
zgrep reads across all rotated .gz log files without expanding them, piping directly to awk and uniq for historical analysis.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding gzip inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
gunzip and gzip -d DELETE the source .gz archive upon successful extraction. If you need to keep the compressed file, always pass the -k (--keep) flag.
Do not extract untrusted .gz files from external sources without testing their compressed-to-uncompressed ratio via gzip -l. Malicious users can construct gzip decompression bombs that expand into hundreds of gigabytes, exhausting server disk space and crashing databases.
When extracting .tar.gz archives using tar, verify that the archive does not contain path traversal members (such as ../../etc/shadow). Modern GNU tar strips leading slashes and prevents path traversal by default.
GNU/Linux, BSD, and BusyBox Implementation Differences
The gunzip command is simply a symbolic link or shell wrapper around gzip -d. Both invocations behave identically across GNU Linux, BSD systems, and Alpine BusyBox.
On Alpine Linux, BusyBox includes gunzip and zcat applets. However, BusyBox gunzip does not support the -k flag in older releases. For universal script portability, streaming via zcat file.gz > file works on every Unix platform.
Troubleshooting Common Errors and Diagnostics
gzip: file.gz: already exists; do you wish to overwrite (y or n)?
Root Cause: The destination uncompressed file already exists in the current directory, and gzip is prompting for confirmation.
Resolution: Pass the -f (--force) flag to overwrite the destination file without prompting.
gunzip -f file.gz
unzip: cannot find zipfile directory in file.gz
Root Cause: The user ran the unzip command (which expects PKZIP .zip format) on a Gzip (.gz) file.
Resolution: Use gunzip or gzip -d instead of unzip.
gunzip file.gz
gzip: file.tar.gz: decompressed into file.tar instead of directory
Root Cause: The file is a tarball (.tar.gz). gunzip only decompresses the gzip layer, leaving the unextracted .tar archive.
Resolution: Extract tarballs using the tar command with the -xzf flags.
tar -xzvf file.tar.gz
Alternatives, Related Commands, and Related Tutorials
- gzip Command in Linux: Compress and Decompress Files with Deflate — Practical syntax, flags, and examples for
gzip. - gunzip Command in Linux: Decompress Gzip Files and Data Streams — Practical syntax, flags, and examples for
gunzip. - Tar Command in Linux: Create, Extract, and Manage Tape Archives — Practical syntax, flags, and examples for
tar. - tee Command in Linux: Split and Redirect Streams with Examples — Practical syntax, flags, and examples for
tee. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!