LFCS 19 🐧 Archives with tar
tar is the standard archiving tool on Linux. It bundles many files and directories into a single archive file, preserving their paths, permissions, ownership, timestamps, and directory structure. The name comes from “tape archive,” a reference to its origins as a tool for writing backups to magnetic tape, but the format survived the tape era because it is simple, portable, and well-suited to sequential access. The LFCS exam tests tar as part of the “Create and manage archives” objective, and the command’s options are among the most commonly tested .
The key distinction is between archiving and compression. tar creates an archive: a single file that contains many files. It does not compress by default. Compression is a separate step, and tar integrates with the standard compressors — gzip, bzip2, and xz — through options that create the compressed archive in one command. The result is a file like backup.tar.gz, which is a gzipped tar archive. The .tar extension indicates the archive format, and the .gz extension indicates the compression method .
The command’s syntax is unusual by modern standards. It uses a mode option — -c for create, -x for extract, -t for list — followed by -f to specify the archive file. The -f option must be followed immediately by the filename, because the filename is its argument. The order of options matters: -cf is correct, -fc is wrong. This is a common source of errors, and the LFCS exam expects fluency with the syntax .
This chapter covers three areas. First, why tar exists and how the archive model works — the problem of bundling many files and the difference between archiving and compression. Second, how to create, list, and extract archives — the -c, -t, and -x modes, the -f option, and the compression options -z, -j, and -J. Third, how to use the common variations — excluding files, extracting specific files, extracting to a different directory, viewing contents before extracting, and the -v option for verbose output. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the archive model.
Key point: tar creates and extracts archives. The three modes are -c (create), -x (extract), and -t (list). The -f option specifies the archive file and must be followed immediately by the filename. Compression is added with -z (gzip), -j (bzip2), or -J (xz). Always use -t to verify an archive before extracting it .
Why tar exists
The bundling problem. A directory tree contains many files, and moving or copying the tree as a unit is difficult with tools that operate on individual files. cp can copy a directory recursively, but it does not preserve all metadata, and it does not produce a single file that can be transferred as a unit. tar solves this by creating a single archive file that contains the entire tree. The archive is portable: it can be copied, transferred, stored, and extracted on another system. The paths, permissions, ownership, and timestamps are preserved .
The metadata problem. A simple concatenation of files would lose the metadata: which bytes belong to which file, what the file’s permissions are, who owns it, and when it was last modified. The tar format stores this metadata in a header before each file’s content. When the archive is extracted, the metadata is restored. This is why tar is the standard tool for backups and for distributing source code: it preserves everything that matters about the files .
The compression problem. Archives are often large, and compression reduces their size. tar does not compress by itself, but it integrates with the standard compressors. The -z option pipes the archive through gzip, -j through bzip2, and -J through xz. The result is a single compressed file that can be transferred more efficiently. The compression is transparent: tar handles the piping, and the user sees a .tar.gz, .tar.bz2, or .tar.xz file .
The streaming problem. tar is designed for sequential access. It reads and writes the archive as a stream, which means it can write to a pipe, a tape device, or a network socket without knowing the total size in advance. This is why tar can be combined with ssh to copy a directory tree to a remote host: tar -czf - . | ssh remote 'tar -xzf - -C /target'. The archive is never written to disk; it flows through the pipe .
The portability problem. The tar format is one of the oldest and most widely supported archive formats. GNU tar, BSD tar, and the tar implementations on every Unix-like system can read each other’s archives, with a few caveats around extended attributes and long path names. The format is simple enough to be implemented everywhere, and the tool is present on every Linux system by default. This universality is why tar remains the standard despite the existence of newer formats like zip and 7z .
The trade-off. tar‘s syntax is archaic. The mode options and the -f argument placement are unlike any modern command-line tool. The option to compress is a single letter, and the choice between -z, -j, and -J is not obvious. The command does not have a --help output that explains the syntax in a friendly way. The trade-off is between the ubiquity and power of the tool and the difficulty of learning its syntax. Once the syntax is learned, it is consistent, and the command is the same on every system.
a. Creating an archive
The create mode is -c. The archive file is specified with -f, and the files and directories to include are listed after the options .
tar -cf backup.tar file1.txt file2.txt directory/
This creates backup.tar containing the two files and the directory tree. The -f option must be followed immediately by the archive name; -cf backup.tar is correct, and -fc backup.tar is wrong.
The -v option adds verbose output, listing each file as it is added:
tar -cvf backup.tar file1.txt file2.txt directory/
The output shows each file’s path as it is archived. This is useful for confirming that the right files are included.
Compression is added with -z for gzip, -j for bzip2, or -J for xz:
tar -czf backup.tar.gz directory/
tar -cjf backup.tar.bz2 directory/
tar -cJf backup.tar.xz directory/
The -z option is the most common. It compresses the archive with gzip, producing a .tar.gz or .tgz file. The -j option uses bzip2, which compresses better but is slower. The -J option uses xz, which compresses even better but is the slowest .
The archive is created from the current directory by default. To create an archive from a different directory, use the -C option:
tar -czf /backup/home.tar.gz -C /home user1
This changes to /home and archives the user1 directory. The paths in the archive are relative to the -C directory, so the archive contains user1/... rather than /home/user1/.... This is important for extraction: the files are extracted relative to the extraction directory, not to the original absolute path .
b. Listing an archive
The list mode is -t. It shows the contents of an archive without extracting it .
tar -tf backup.tar
The output lists each file’s path. The -v option adds details:
tar -tvf backup.tar
The verbose listing shows the permissions, owner, group, size, and modification time of each file, in a format similar to ls -l.
Listing is the recommended first step before extraction. It confirms that the archive contains what is expected, and it shows the exact paths. If the archive contains absolute paths or ../ components, extraction may write outside the intended directory. The -t listing reveals this before it happens .
For a compressed archive, the same compression option used to create it is used to list it:
tar -tzf backup.tar.gz
tar -tjf backup.tar.bz2
tar -tJf backup.tar.xz
The compression option must match the archive. If the archive is gzipped and -j is used, tar reports an error. Modern GNU tar can often auto-detect the compression, but the explicit option is more reliable .
c. Extracting an archive
The extract mode is -x. It extracts the archive’s contents into the current directory by default .
tar -xf backup.tar
This extracts all files, recreating the directory structure and restoring the metadata. The -v option lists each file as it is extracted:
tar -xvf backup.tar
The -C option extracts to a different directory:
tar -xzf backup.tar.gz -C /tmp/restore
The directory must exist before extraction. The -C option changes to the directory and extracts there, preserving the relative paths from the archive .
To extract only specific files, list them after the archive name:
tar -xf backup.tar path/to/file1.txt path/to/file2.txt
The paths must match the paths in the archive. The -t listing shows the exact paths to use.
To extract a compressed archive, the compression option must match:
tar -xzf backup.tar.gz
tar -xjf backup.tar.bz2
tar -xJf backup.tar.xz
The extraction recreates the directory structure, the file permissions, and the ownership (if the extracting user has the privileges to set it). Timestamps are restored by default. The --no-same-owner option prevents ownership restoration, which is useful when extracting as a non-root user .
Complete Example Session
# ============================================
# PART 1: CREATE AN ARCHIVE
# ============================================
tar -cf backup.tar file1.txt file2.txt
# Creates backup.tar containing the two files.
# ============================================
# PART 2: CREATE WITH VERBOSE OUTPUT
# ============================================
tar -cvf backup.tar file1.txt file2.txt
# Output:
# file1.txt
# file2.txt
# ============================================
# PART 3: CREATE A COMPRESSED ARCHIVE
# ============================================
tar -czf backup.tar.gz directory/
# Creates backup.tar.gz, gzip-compressed.
# ============================================
# PART 4: CREATE WITH BZIP2 AND XZ
# ============================================
tar -cjf backup.tar.bz2 directory/ # bzip2
tar -cJf backup.tar.xz directory/ # xz
# ============================================
# PART 5: CREATE FROM A DIFFERENT DIRECTORY
# ============================================
tar -czf /backup/home.tar.gz -C /home user1
# Changes to /home, archives user1.
# The archive contains user1/... paths.
# ============================================
# PART 6: LIST AN ARCHIVE
# ============================================
tar -tf backup.tar
# Output:
# file1.txt
# file2.txt
# ============================================
# PART 7: LIST WITH DETAILS
# ============================================
tar -tvf backup.tar
# Output:
# -rw-r--r-- user/user 1024 2025-01-01 12:00 file1.txt
# -rw-r--r-- user/user 2048 2025-01-01 12:00 file2.txt
# ============================================
# PART 8: LIST A COMPRESSED ARCHIVE
# ============================================
tar -tzf backup.tar.gz
# ============================================
# PART 9: EXTRACT AN ARCHIVE
# ============================================
tar -xf backup.tar
# Extracts all files into the current directory.
tar -xzf backup.tar.gz -C /tmp/restore
# Extracts into /tmp/restore.
tar -xf backup.tar path/to/file1.txt
# Extracts only the specified file.
# ============================================
# PART 10: THE LFCS PIPELINE
# ============================================
# Back up /etc to a compressed archive
tar -czf /backup/etc-$(date +%F).tar.gz /etc
# Verify the archive before relying on it
tar -tzf /backup/etc-$(date +%F).tar.gz | head
# Extract a single file from the archive
tar -xzf /backup/etc-$(date +%F).tar.gz etc/ssh/sshd_config -C /tmp
# Copy a directory tree to a remote host without an intermediate file
tar -czf - /home/user1 | ssh remote 'tar -xzf - -C /backup'
# Exclude files from the archive
tar -czf /backup/home.tar.gz --exclude='*.tmp' --exclude='.cache' /home/user1
The ten parts show creating an archive, creating with verbose output, creating a compressed archive, bzip2 and xz compression, creating from a different directory, listing an archive, listing with details, listing a compressed archive, extracting an archive, and the LFCS pipeline scenarios.
Quick Reference
Modes
| Mode | Meaning |
|---|---|
-c | Create an archive |
-x | Extract an archive |
-t | List the contents |
-r | Append to an archive |
-u | Update files in an archive |
Common Options
| Option | Meaning |
|---|---|
-f FILE | Archive file name (must follow immediately) |
-v | Verbose output |
-z | gzip compression |
-j | bzip2 compression |
-J | xz compression |
-C DIR | Change to directory |
--exclude=PATTERN | Exclude files matching pattern |
--no-same-owner | Do not restore ownership |
-p | Preserve permissions |
Compression Options
| Option | Compressor | Extension | Speed | Ratio |
|---|---|---|---|---|
-z | gzip | .tar.gz, .tgz | Fast | Good |
-j | bzip2 | .tar.bz2 | Slow | Better |
-J | xz | .tar.xz | Slowest | Best |
| (none) | none | .tar | Fastest | None |
Common Commands
| Command | Purpose |
|---|---|
tar -cf archive.tar files | Create uncompressed archive |
tar -czf archive.tar.gz dir/ | Create gzipped archive |
tar -tf archive.tar | List contents |
tar -tvf archive.tar | List with details |
tar -xf archive.tar | Extract |
tar -xzf archive.tar.gz -C /dir | Extract to directory |
tar -xzf archive.tar.gz file | Extract one file |
Best Practices
✅ Do This:
# Use -t to verify before extracting
tar -tzf backup.tar.gz | head # ✅
# Use -C to extract to a specific directory
tar -xzf backup.tar.gz -C /tmp/restore # ✅
# Use -C to create from a specific directory
tar -czf /backup/home.tar.gz -C /home user1 # ✅
# Use --exclude to skip unwanted files
tar -czf backup.tar.gz --exclude='*.tmp' /home/user1 # ✅
# Use -p to preserve permissions when extracting as root
tar -xpf backup.tar # ✅
# Quote the date in the filename
tar -czf /backup/etc-$(date +%F).tar.gz /etc # ✅
❌ Don’t Do This:
# Don't use -fc instead of -cf
tar -fc backup.tar file.txt # wrong option order # ❌
# Don't extract without listing first
tar -xf unknown.tar # may contain absolute paths or ../ # ❌
# Don't use absolute paths when creating
tar -cf backup.tar /home/user1 # archive contains /home/user1 # ❌
# Don't mismatch compression options
tar -xzf backup.tar.bz2 # wrong compressor # ❌
# Don't forget -f and the filename
tar -c file.txt # tar tries to write to default tape # ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
tar: Refusing to read archive contents | Wrong compression option | Match -z, -j, -J to the archive |
tar: backup.tar: Cannot open | -f not followed by filename | Use -cf backup.tar, not -fc |
| Files extracted to wrong location | Absolute paths in archive | Use -C to target directory |
| Permissions not restored | Extracting as non-root | Use -p or extract as root |
| Archive larger than expected | Not using compression | Add -z |
| Slow extraction | Using -J on a large archive | Use -z for speed |
| Unwanted files in archive | No --exclude | Add --exclude patterns |
tar: Exiting with failure status | File not found | Check paths |
Real-World Examples
1. Create an Archive
tar -cf backup.tar file1.txt file2.txt
2. Create a Gzipped Archive
tar -czf backup.tar.gz directory/
3. List an Archive
tar -tf backup.tar
4. List with Details
tar -tvf backup.tar
5. Extract an Archive
tar -xf backup.tar
6. Extract to a Directory
tar -xzf backup.tar.gz -C /tmp/restore
7. Extract a Single File
tar -xf backup.tar path/to/file.txt
8. Exclude Files
tar -czf backup.tar.gz --exclude='*.tmp' /home/user1
9. Create from a Directory
tar -czf /backup/home.tar.gz -C /home user1
10. Remote Copy via Pipe
tar -czf - /home/user1 | ssh remote 'tar -xzf - -C /backup'
Visual
Archive vs Compression
┌──────────────────────────────────────────────────────────────┐
│ ARCHIVE vs COMPRESSION │
│ │
│ Files: │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ file1.txt│ │ file2.txt│ │ dir/ │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │ │ │ │
│ └────────────┼────────────┘ │
│ ▼ │
│ tar -cf backup.tar file1.txt file2.txt dir/ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ backup.tar │ │
│ │ (uncompressed archive) │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ tar -czf backup.tar.gz file1.txt file2.txt dir/ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ backup.tar.gz │ │
│ │ (gzip-compressed archive) │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ tar bundles files. Compression is a separate step, │
│ integrated with -z, -j, or -J. │
│ │
└──────────────────────────────────────────────────────────────┘
Create, List, Extract
┌──────────────────────────────────────────────────────────────┐
│ CREATE, LIST, EXTRACT │
│ │
│ CREATE: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -czf backup.tar.gz directory/ │ │
│ │ │ │
│ │ -c create │ │
│ │ -z gzip │ │
│ │ -f filename │ │
│ │ directory/ what to archive │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ LIST: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -tzf backup.tar.gz │ │
│ │ │ │
│ │ -t list │ │
│ │ -z gzip │ │
│ │ -f filename │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ EXTRACT: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -xzf backup.tar.gz -C /tmp/restore │ │
│ │ │ │
│ │ -x extract │ │
│ │ -z gzip │ │
│ │ -f filename │ │
│ │ -C target directory │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
Compression Options
┌──────────────────────────────────────────────────────────────┐
│ COMPRESSION OPTIONS │
│ │
│ gzip (-z): │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -czf backup.tar.gz dir/ │ │
│ │ Fast compression, good ratio, most common │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ bzip2 (-j): │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -cjf backup.tar.bz2 dir/ │ │
│ │ Slower, better ratio │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ xz (-J): │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -cJf backup.tar.xz dir/ │ │
│ │ Slowest, best ratio │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ The compression option must match between create, list, │
│ and extract. Modern GNU tar auto-detects in many cases. │
│ │
└──────────────────────────────────────────────────────────────┘
The -C Option
┌──────────────────────────────────────────────────────────────┐
│ THE -C OPTION │
│ │
│ CREATE: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -czf /backup/home.tar.gz -C /home user1 │ │
│ │ │ │
│ │ 1. Change to /home │ │
│ │ 2. Archive user1 │ │
│ │ 3. Archive contains user1/... not /home/user1/... │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ EXTRACT: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ tar -xzf backup.tar.gz -C /tmp/restore │ │
│ │ │ │
│ │ 1. Change to /tmp/restore │ │
│ │ 2. Extract the archive │ │
│ │ 3. Files are created under /tmp/restore │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ The -C option is available in all modes. │
│ It is essential for extracting to a specific location │
│ without changing the current directory. │
│ │
└──────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
tar | Archive tool |
| Create | -c |
| Extract | -x |
| List | -t |
| Archive file | -f FILE (must follow immediately) |
| Verbose | -v |
| gzip | -z |
| bzip2 | -j |
| xz | -J |
| Change directory | -C DIR |
| Exclude | --exclude=PATTERN |
| Preserve permissions | -p |
Key takeaways:
tarbundles files into a single archive. It preserves paths, permissions, ownership, and timestamps. The archive is portable and can be transferred as a unit. The command does not compress by default; compression is added with-z,-j, or-J.- The three modes are
-c,-x, and-t. Create (-c) makes an archive, extract (-x) unpacks it, and list (-t) shows its contents. The-foption specifies the archive file and must be followed immediately by the filename . - The
-foption placement matters.-cf backup.taris correct;-fc backup.taris wrong. The filename is the argument to-f, so it must come immediately after thef. - Compression options are
-z,-j, and-J.-zuses gzip (fast, good ratio),-juses bzip2 (slower, better ratio), and-Juses xz (slowest, best ratio). The compression option must match between create, list, and extract . - Always list an archive before extracting. The
-tmode shows the paths in the archive. If the archive contains absolute paths or../components, extraction may write outside the intended directory. Listing reveals this before it happens . - The
-Coption changes the working directory. In create mode, it determines the base for the archived paths. In extract mode, it determines the target directory. This is the standard way to control where the archive is created from and where it is extracted to . - The
--excludeoption skips files. It accepts a pattern, and it can be repeated. This is useful for excluding temporary files, caches, and other data that should not be archived . tarcan stream through a pipe.tar -czf - . | ssh remote 'tar -xzf - -C /target'copies a directory tree to a remote host without an intermediate file. The-as the filename means standard input or output .
Remember: tar is the standard archiving tool on Linux. It bundles many files into a single archive, preserving metadata, and integrates with the standard compressors. The three modes are -c for create, -x for extract, and -t for list. The -f option specifies the archive file and must be followed immediately by the filename. Compression is added with -z, -j, or -J. Always list an archive before extracting it, and use -C to control the directory. For the LFCS exam, the key patterns are creating a compressed archive, listing its contents, extracting to a specific directory, and excluding files. The syntax is archaic, but once learned, it is consistent across every Linux system.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!