tar

Archive multiple files into a single file, optionally compressing them.

What it does

tar (tape archive) collects many files and directories into a single archive file. It can also compress that archive using gzip, bzip2, or xz.

How it works (mechanical)

Quick Start

# Create archive
tar -cvf archive.tar file1 file2

# Extract archive
tar -xvf archive.tar

# List contents
tar -tvf archive.tar

Core Options (Most Useful Flags)

-c   Create archive
-x   Extract archive
-t   List contents
-f   Specify archive file
-v   Verbose output

-z   Use gzip (.tar.gz)
-j   Use bzip2 (.tar.bz2)
-J   Use xz (.tar.xz)

-C DIR   Change to directory before operation
--exclude="PATTERN"   Skip files
--wildcards           Use patterns
--remove-files        Delete originals after archiving

Compression Modes

.tar       No compression
.tar.gz    gzip (fast, common)
.tar.bz2   bzip2 (better compression, slower)
.tar.xz    xz (best compression, slowest)

12 Practical Examples

# 1) Create archive
tar -cvf files.tar file1.txt file2.txt
# 2) Archive a directory
tar -cvf project.tar project/
# 3) Create gzip archive
tar -czvf project.tar.gz project/
# 4) Extract gzip archive
tar -xzvf project.tar.gz
# 5) List contents
tar -tvf archive.tar
# 6) Extract to directory
tar -xvf archive.tar -C /tmp/
# 7) Create xz compressed archive
tar -cJvf backup.tar.xz /home/user
# 8) Exclude files
tar -czvf backup.tar.gz /home --exclude="*.log"
# 9) Archive from find
find . -type f -name "*.txt" -print0 | xargs -0 tar -cvf textfiles.tar
# 10) Append files
tar -rvf archive.tar newfile.txt
# 11) Extract single file
tar -xvf archive.tar file1.txt
# 12) Remove original files after archiving
tar -cvf archive.tar file1.txt --remove-files

Very Useful Real-World Patterns

# Backup home directory
tar -czvf home_backup.tar.gz /home/user
# Backup and exclude cache/logs
tar -czvf backup.tar.gz /var/www \
--exclude="*.log" \
--exclude="cache"
# Extract and overwrite existing files
tar -xvf archive.tar --overwrite
# Create archive from list of files
cat filelist.txt | xargs tar -cvf archive.tar

Notes & Gotchas

Safety Pattern

# Preview before extracting
tar -tvf archive.tar

# Then extract
tar -xvf archive.tar

Historical Context

tar originated for writing data to tape drives. It remains a core Unix tool for packaging and transferring collections of files.

Modern Equivalent

Modern tools like zip, 7z, and GUI archive managers exist, but tar remains standard in Linux systems and scripting.

Related Commands