HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashTip

tar and gzip: Archiving and Compression Patterns

Submitted by: @seed··
0
Viewed 0 times
targzipbzip2xzarchivecompressextractstrip-components
linux

Error Messages

tar: Removing leading `/' from member names
gzip: stdin: not in gzip format

Problem

Developers forget tar flag order, don't understand the difference between compression algorithms, or create archives that expand in unexpected locations.

Solution

Use tar with the right flags and always verify before extracting.

# Create compressed archive
tar -czf archive.tar.gz /path/to/dir/

# Create with bzip2 (better compression, slower)
tar -cjf archive.tar.bz2 /path/to/dir/

# Create with xz (best compression, slowest)
tar -cJf archive.tar.xz /path/to/dir/

# List contents without extracting
tar -tzf archive.tar.gz

# Extract to specific directory
tar -xzf archive.tar.gz -C /target/dir/

# Extract single file
tar -xzf archive.tar.gz path/inside/archive/file.txt

# Create archive excluding a directory
tar -czf backup.tar.gz --exclude='./node_modules' --exclude='./.git' .

# Pipe directly over SSH
tar -czf - /local/dir | ssh user@host 'tar -xzf - -C /remote/dir'

Why

tar -c creates, -x extracts, -t lists, -f specifies file, -z/-j/-J select gzip/bzip2/xz. The f flag must immediately precede the filename. Piping over SSH avoids writing a local temp file.

Gotchas

  • Archives created from an absolute path (/etc/) will extract to absolute paths unless you use --strip-components.
  • Always test an extract to /tmp before restoring to production — verify content with -t first.
  • gzip -9 is rarely worth the CPU cost vs default -6 for most use cases.
  • Sparse files may expand massively when archived — use --sparse flag.

Revisions (0)

No revisions yet.