On this page 12 sections
  1. tar vs gzip
  2. Create a tar archive
  3. Create a compressed tar.gz archive
  4. Extract archives
  5. List contents without extracting
  6. Extract a single file
  7. Exclude files or directories
  8. gzip individual files
  9. Keep original file
  10. Compression level
  11. Read compressed text without extracting
  12. Useful backup example
01

tar vs gzip

tar groups multiple files and directories into a single archive. gzip compresses data. A .tar.gz file therefore combines both operations: tar creates the archive and gzip compresses it.

02

Create a tar archive

The common tar flags are c for create, v for verbose and f for archive filename.

Create archive
tar -cvf backup.tar /opt/sam0x
Create without verbose output
tar -cf backup.tar /opt/sam0x
03

Create a compressed tar.gz archive

The z option enables gzip compression while creating or extracting a tar archive.

Create tar.gz
tar -czvf backup.tar.gz /opt/sam0x
Compact version
tar -czf backup.tar.gz /opt/sam0x
04

Extract archives

The x option extracts an archive. gzip-compressed tar archives use z as well.

Extract tar
tar -xvf backup.tar
Extract tar.gz
tar -xzvf backup.tar.gz
Extract into directory
tar -xzf backup.tar.gz -C /tmp/restore
05

List contents without extracting

The t option lists files inside the archive. This is useful before extracting unknown archives.

Inspect tar
tar -tf backup.tar
Inspect tar.gz
tar -tzf backup.tar.gz
06

Extract a single file

A specific path inside the archive can be extracted without unpacking everything.

Extract one file
tar -xzf backup.tar.gz opt/sam0x/config.conf
07

Exclude files or directories

--exclude prevents selected paths or patterns from being included in the archive.

Exclude logs
tar -czf backup.tar.gz --exclude="*.log" /opt/sam0x
Exclude cache directory
tar -czf backup.tar.gz --exclude="/opt/sam0x/cache" /opt/sam0x
08

gzip individual files

gzip compresses a single file and normally replaces it with a .gz version.

Compress file
gzip access.log
Decompress file
gunzip access.log.gz
09

Keep original file

-k keeps the original file instead of replacing it.

Compress and keep source
gzip -k access.log
10

Compression level

gzip supports compression levels from -1 to -9. Lower values are faster while higher values spend more time attempting better compression.

Fast compression
gzip -1 large.log
Maximum gzip compression
gzip -9 large.log
11

Read compressed text without extracting

zcat, zgrep and related tools can inspect compressed files directly.

Print compressed log
zcat access.log.gz
Search compressed log
zgrep -i "error" access.log.gz
12

Useful backup example

tar is frequently used to create quick backups of application directories before making changes.

Timestamped backup
tar -czf sam0x-backup-$(date +%F).tar.gz /opt/sam0x