Tar Command Essential Guide | Generated by AI

Home 2026.02

The tar command (short for “tape archive”) is a fundamental Unix/Linux utility for bundling multiple files and directories into a single archive file. Here’s a comprehensive introduction:

Basic Concept

Tar creates archive files that preserve file permissions, ownership, directory structures, and timestamps. Unlike compression tools, tar itself doesn’t compress—it just bundles files together. However, it’s commonly used with compression tools like gzip or bzip2.

Common Usage Patterns

Creating archives:

tar -cvf archive.tar files/          # Create archive
tar -czvf archive.tar.gz files/      # Create + gzip compress
tar -cjvf archive.tar.bz2 files/     # Create + bzip2 compress

Extracting archives:

tar -xvf archive.tar                 # Extract
tar -xzvf archive.tar.gz             # Extract gzipped
tar -xjvf archive.tar.bz2            # Extract bzip2'd
tar -xvf archive.tar -C /target/dir  # Extract to specific directory

Viewing contents:

tar -tvf archive.tar                 # List files without extracting
tar -tzvf archive.tar.gz             # List files in gzipped archive

Key Options

Practical Examples

Backup a directory:

tar -czvf backup-$(date +%Y%m%d).tar.gz /home/user/documents/

Extract specific files:

tar -xzvf archive.tar.gz file1.txt dir/file2.txt

Exclude certain files:

tar -czvf archive.tar.gz --exclude='*.log' --exclude='node_modules' project/

Extract to different location:

tar -xzvf archive.tar.gz -C /opt/extracted/

View file before extracting:

tar -tzvf archive.tar.gz | grep specific-file

Modern Simplification

Modern tar versions can auto-detect compression, so you can often omit the compression flag:

tar -xvf archive.tar.gz    # Auto-detects gzip
tar -xvf archive.tar.bz2   # Auto-detects bzip2

Common Gotchas

The order of options matters with -f. The filename must immediately follow -f, so tar -cvzf archive.tar.gz files/ works, but tar -cvfz archive.tar.gz files/ might not.

When extracting, tar preserves the original directory structure. If the archive contains folder/file.txt, it will create that structure, not just extract file.txt to the current directory.


Back Donate