SH

Archives & Compression

Bash & Linux · 7 entries

Create a Tar Archive

syntax
tar -cf archive.tar files...
tar -czf archive.tar.gz files...
example
tar -czf backup_20260404.tar.gz /opt/app/data/ /opt/app/config/
tar -cjf source.tar.bz2 --exclude='.git' --exclude='node_modules' project/

Note -c creates, -z compresses with gzip, -j with bzip2, -J with xz. -f must be followed by the archive name. --exclude omits patterns. Always put -f last among the single-letter flags or use the long form to avoid mistakes.

Extract a Tar Archive

syntax
tar -xf archive.tar [-C directory]
example
tar -xzf backup_20260404.tar.gz -C /opt/restore/
tar -xf release.tar.bz2
tar -tf archive.tar.gz

Note -x extracts, -C specifies the target directory. tar auto-detects compression on modern systems, so -xf often works without specifying -z/-j/-J. -t lists contents without extracting (always do this first on untrusted archives). WARNING: Tar archives can contain absolute paths or ../ that overwrite files outside the target; use -t to inspect first.

Gzip Compress & Decompress

syntax
gzip [options] file
gunzip file.gz
example
gzip access.log
gunzip access.log.gz
gzip -k -9 database.sql

Note gzip replaces the original file by default. -k keeps the original. -9 uses maximum compression (slower). -d decompresses (same as gunzip). gzip compresses single files; combine with tar for directories.

Zip Archive

syntax
zip [options] archive.zip files...
unzip [options] archive.zip
example
zip -r project.zip project/ -x '*.git*'
unzip project.zip -d /opt/builds/
unzip -l project.zip

Note -r is required for directories. -x excludes patterns. unzip -l lists contents without extracting. -d specifies the extraction directory. zip is the most portable format for sharing with Windows and macOS users.

Bzip2 Compression

syntax
bzip2 [options] file
bunzip2 file.bz2
example
bzip2 -k large_dataset.csv
bunzip2 archive.bz2

Note Bzip2 achieves better compression ratios than gzip but is slower. -k keeps the original file. Like gzip, it handles single files; pair with tar for directories.

XZ Compression

syntax
xz [options] file
unxz file.xz
example
xz -9 -k firmware.bin
tar -cJf logs.tar.xz /var/log/app/
unxz data.xz

Note xz provides the best compression ratio among common tools but uses the most CPU and memory. -9 is maximum compression. Often used for distributing large software packages (e.g., Linux kernel tarballs).

Read Compressed Files Without Extracting

syntax
zcat file.gz
zgrep pattern file.gz
example
zcat access.log.2.gz | tail -100
zgrep 'error 500' /var/log/nginx/access.log.*.gz

Note zcat works like cat on gzipped files. zgrep searches inside gzipped files. zless lets you page through them. These save time and disk space when investigating rotated log files.