Managing files efficiently is critical in Linux. Whether you’re freeing up space or sharing data, knowing compression/decompression commands is essential. Here’s a detailed breakdown:
1. gzip / gunzip
Best for: Fast compression/decompression (uses .gz
format).
Compress:
gzip filename.txt # Creates filename.txt.gz
Decompress:
gunzip filename.txt.gz
# OR
gzip -d filename.txt.gz
Keep original file: Use -k
flag (e.g., gzip -k file.txt
).
2. bzip2 / bunzip2
Best for: Smaller file sizes than gzip (slower; uses .bz2
).
Compress:
bzip2 filename.txt # Creates filename.txt.bz2
Decompress:
bunzip2 filename.txt.bz2
# OR
bzip2 -d filename.txt.bz2
Preserve original: Add -k
(e.g., bzip2 -k file.txt
).
3. xz / unxz
Best for: Maximum compression (uses .xz
; slower but efficient).
Compress:
xz filename.txt # Creates filename.txt.xz
Decompress:
unxz filename.txt.xz
# OR
xz -d filename.txt.xz
Keep original: Use -k
(e.g., xz -k file.txt
).
4. zip / unzip
Best for: Cross-platform compatibility (Windows/macOS/Linux).
Compress files/directories:
zip archive.zip file1.txt folder/ # Include multiple items
Decompress:
unzip archive.zip
Extract to specific folder:
unzip archive.zip -d /target/path
5. tar (Tape Archive)
Best for: Bundling directories + compression support.
Create archive (no compression):
tar -cvf archive.tar /path/to/folder
Extract archive:
tar -xvf archive.tar
Compress with gzip (.tar.gz
):
tar -czvf archive.tar.gz /path/to/folder
Compress with xz (.tar.xz
):
tar -cJvf archive.tar.xz /path/to/folder
Extract compressed archives:
tar -xzvf archive.tar.gz # .gz
tar -xjvf archive.tar.bz2 # .bz2
tar -xJvf archive.tar.xz # .xz
Key Flags Explained
-c
: Create archive-x
: Extract archive-v
: Verbose (show progress)-f
: Specify filename-z
: Use gzip compression-j
: Use bzip2 compression-J
: Use xz compression
When to Use Which?
- Speed:
gzip
(fastest) →bzip2
→xz
(slowest). - Space savings:
xz
(best) →bzip2
→gzip
. - Windows compatibility:
zip
. - Directories: Always use
tar
+ compression.
Practice these commands to master Linux file management! 💻🔧