Tar Command in Linux: Create, Extract, and Manage Tape Archives
Learn tar command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn tar command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What tar Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Interactive Builder for this Guide
Build your custom tar syntax (Tar Command in Linux: Create, Extract, and Manage Tape Archives)
tar -czvf backup.tar.gz --exclude=node_modules /var/www/html
-cCreate a new tar archive-zCompress/decompress using gzip (.tar.gz)-vVerbose output listing processed paths-f backup.tar.gzSpecify the archive file path--exclude=node_modulesSkip matching files or foldersMastering the tar command in linux is a core competency for every systems administrator, software developer, and DevOps practitioner. Originally developed in early Unix for writing sequential file streams to magnetic tape drives—hence 'Tape Archive'—tar remains the universal standard for packaging software distribution bundles, creating full system backups, and archiving directory hierarchies across Linux distributions.
The tar command in Linux creates, maintains, modifies, and extracts tape archive files (tarballs) that bundle multiple files and directories into a single container file. Run tar -czvf archive.tar.gz /path/to/dir to create a compressed gzip archive, tar -xzvf archive.tar.gz to extract it, or tar -tf archive.tar.gz to inspect its contents without extracting.
Unlike standalone compression utilities like gzip or bzip2 which only compress individual files, tar bundles hundreds of thousands of files and directories into a single archive stream, preserving critical filesystem metadata including POSIX permission bits, ownership (UID/GID), modification timestamps, symbolic links, and directory hierarchies.
Modern GNU tar seamlessly integrates transparent compression filters: adding -z compresses via gzip (.tar.gz), -j compresses via bzip2 (.tar.bz2), -J compresses via xz (.tar.xz), and --zstd compresses via Zstandard. Understanding tar's operation modes, extraction switches, and safety rules ensures you can package and restore server data with complete reliability.
What tar Does and When to Use It
Under the hood, a tar archive consists of a sequence of fixed-size 512-byte blocks. Each archived file or directory begins with a 512-byte header block formatted according to POSIX ustar (Uniform Standard Tar) or GNU tar specifications. The header contains essential file attributes: file name, file mode (permissions), UID, GID, file size in octal, modification time (mtime), checksum, type flag (regular file, symlink, directory, character/block device, FIFO), and link target path.
Following the header block, the file's raw byte content is written, padded with null bytes to align with the nearest 512-byte boundary. The end of the archive is marked by two consecutive 512-byte blocks of null bytes. When combined with compression flags (-z, -j, -J), GNU tar creates a bi-directional pipe, transparently spawning the corresponding compressor binary (gzip, bzip2, xz) as a child process and streaming blocks through it via pipe(2) and dup2(2) before writing to the target archive file.
Under the hood, tar gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -c, -x, -t, -v turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The tar utility is packaged in tar across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether tar is installed and inspect which binary path and version your shell resolves:
type -a tar
tar --version 2>/dev/null || man -f tar
# Illustrative output (reviewed against documentation)
tar is /usr/bin/tar
tar (tar)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y tar
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y tar
# Arch Linux
sudo pacman -S --noconfirm tar
# Alpine Linux
sudo apk add --no-cache tar
Command Syntax, Arguments, and Exit Status Codes
tar [OPERATION] [OPTIONS] -f ARCHIVE [FILE...]
GNU tar syntax requires specifying exactly one main operation mode: -c (--create), -x (--extract), -t (--list), -r (--append), or -u (--update), followed by the -f (--file) option specifying the archive path, and any file or directory targets.
Traditionally, tar supports three option syntax styles: traditional options without leading dashes (e.g. tar czvf archive.tar.gz dir), standard POSIX short options with a dash (e.g. tar -czvf archive.tar.gz dir), and GNU long options (e.g. tar --create --gzip --file=archive.tar.gz dir). In modern shell scripts, using leading dashes is standard practice.
0— Successful completion; archive created, listed, or extracted without error.1— Some files differ or were modified during archiving (warning status).2— Fatal operational error; archive corrupted, permission denied, or file unreadable.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-c | --create | Create a new tar archive. |
-x | --extract, --get | Extract files from an archive. |
-t | --list | List the contents of an archive without extracting. |
-v | --verbose | Verbosely list files processed during creation or extraction. |
-f ARCHIVE | --file=ARCHIVE | Use archive file ARCHIVE (defaults to /dev/tape on traditional Unix). |
-z | --gzip | Filter the archive through gzip (.tar.gz, .tgz). |
-j | --bzip2 | Filter the archive through bzip2 (.tar.bz2). |
-J | --xz | Filter the archive through xz (.tar.xz). |
-C DIR | --directory=DIR | Change to directory DIR before performing operations. |
-p | --preserve-permissions | Extract file permissions (default for superuser). |
The -f option is mandatory whenever reading from or writing to a disk file. If -f is omitted, traditional tar attempts to read from or write to the system's default tape drive device (often /dev/tape), causing an immediate failure on modern cloud instances.
The -C (--directory) option is essential for safe extraction. Running tar -xzvf archive.tar.gz -C /opt/app/ extracts contents directly into /opt/app/ without requiring you to cd into that directory first, preventing stray files from cluttering your current working directory.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Create a Compressed .tar.gz Archive of a Directory
Package and compress an entire web project directory using gzip compression.
tar -czvf project_backup.tar.gz /var/www/myproject
# Illustrative output (reviewed against documentation)
tar: Removing leading '/' from member names
/var/www/myproject/
/var/www/myproject/index.html
/var/www/myproject/css/style.css
/var/www/myproject/js/app.js
The -c creates the archive, -z applies gzip, -v lists files as they are packed, and -f specifies the archive name.
2. Extract a .tar.gz Archive into a Specific Directory with -C
Extract an archived package directly into a target deployment folder.
tar -xzvf project_backup.tar.gz -C /opt/deployment/
# Illustrative output (reviewed against documentation)
var/www/myproject/
var/www/myproject/index.html
var/www/myproject/css/style.css
var/www/myproject/js/app.js
The -x extracts files, -z handles gzip decompression, and -C /opt/deployment/ changes target path prior to extraction.
3. List Archive Contents Without Extracting Using -t
Inspect the file list inside an archive without expanding files on disk.
tar -tvf project_backup.tar.gz
# Illustrative output (reviewed against documentation)
drwxr-xr-x ubuntu/ubuntu 0 2026-10-22 14:00 var/www/myproject/
-rw-r--r-- ubuntu/ubuntu 1842 2026-10-22 14:00 var/www/myproject/index.html
-rw-r--r-- ubuntu/ubuntu 450 2026-10-22 14:00 var/www/myproject/css/style.css
The -t flag lists file metadata including permissions, ownership, byte sizes, and modification dates.
4. Extract a Single Specific File from an Archive
Extract only one configuration file from a multi-gigabyte tar archive.
tar -xzvf project_backup.tar.gz var/www/myproject/index.html
# Illustrative output (reviewed against documentation)
var/www/myproject/index.html
Specifying the exact archive member path after the archive filename extracts only that individual file.
5. Exclude Unwanted Files and Directories During Creation
Create an archive while ignoring .git version control and temporary cache directories.
tar --exclude='.git' --exclude='node_modules' --exclude='*.log' -czvf app.tar.gz ./myproject
# Illustrative output (reviewed against documentation)
./myproject/
./myproject/src/
./myproject/package.json
The --exclude option prunes matching directories and file patterns from the resulting archive.
6. Create a High-Compression .tar.xz Archive Using -J
Create an archive with xz compression for maximum storage efficiency.
tar -cJvf system_config.tar.xz /etc/
# Illustrative output (reviewed against documentation)
tar: Removing leading '/' from member names
etc/
etc/hosts
etc/resolv.conf
The -J flag applies xz compression (LZMA2 algorithm), which produces smaller files than gzip for cold storage.
Real-World Workflows, Pipelines, and Shell Automation
Pre-Upgrade Full Server Configuration Backup
Create a timestamped root configuration backup preserving permissions before applying major OS upgrades.
#!/usr/bin/env bash
set -euo pipefail
BACKUP_DIR="/var/backups/system"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE_PATH="$BACKUP_DIR/etc_backup_$TIMESTAMP.tar.gz"
mkdir -p "$BACKUP_DIR"
echo "Creating system configuration backup at: $ARCHIVE_PATH..."
# -p: preserve permissions, -z: gzip, -c: create
sudo tar -cpzf "$ARCHIVE_PATH" \
--exclude='etc/udev/rules.d/70-persistent-net.rules' \
/etc
echo "Backup complete. Verifying archive integrity..."
tar -tzf "$ARCHIVE_PATH" > /dev/null
echo "[SUCCESS] Verified archive integrity: $(du -h "$ARCHIVE_PATH" | cut -f1)"
# Illustrative output (reviewed against documentation)
Creating system configuration backup at: /var/backups/system/etc_backup_20261022_153000.tar.gz...
Backup complete. Verifying archive integrity...
[SUCCESS] Verified archive integrity: 18M
Using -p preserves exact permission bits and file ownership, critical for restoring /etc safely after an outage.
Zero-Downtime Application Release Packaging and Deployment
Package application artifacts in CI and deploy them into production with atomic symlink switching.
#!/usr/bin/env bash
set -euo pipefail
RELEASE_ID=$(date +%Y%m%d%H%M%S)
RELEASE_DIR="/var/www/releases/$RELEASE_ID"
CURRENT_LINK="/var/www/current"
mkdir -p "$RELEASE_DIR"
echo "Extracting release bundle into $RELEASE_DIR..."
tar -xzf /tmp/release.tar.gz -C "$RELEASE_DIR"
echo "Executing atomic symlink switch to release $RELEASE_ID..."
ln -sfn "$RELEASE_DIR" "$CURRENT_LINK"
echo "Reloading Nginx server..."
sudo systemctl reload nginx
echo "[DEPLOYED] Production traffic switched to release $RELEASE_ID."
# Illustrative output (reviewed against documentation)
Extracting release bundle into /var/www/releases/20261022153500...
Executing atomic symlink switch to release 20261022153500...
Reloading Nginx server...
[DEPLOYED] Production traffic switched to release 20261022153500.
tar -xzf -C extracts the artifact into an isolated release directory, enabling instant zero-downtime symlink deployment.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding tar inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Be cautious when extracting untrusted archives. A 'tar bomb' is an archive containing hundreds of files in its root rather than within a single parent directory, which will clutter your current working directory. Always inspect archives with tar -tf first.
GNU tar automatically strips leading slashes ('/') from file paths by default (reporting 'Removing leading / from member names'). This prevents malicious archives from overwriting system files like /etc/passwd via absolute path traversal. Never disable this protection with -P (--absolute-names) unless restoring a full system backup in rescue mode.
When running tar with sudo privileges to extract untrusted third-party archives, attackers can craft archives containing setuid binaries or device nodes. Pass --no-same-owner and --no-same-permissions when extracting untrusted files to neutralize privilege escalation vectors.
GNU/Linux, BSD, and BusyBox Implementation Differences
GNU tar is standard on Linux distributions. On macOS and FreeBSD, the default tar is BSD tar (based on libarchive). While basic options (-c, -x, -t, -v, -f, -z, -j, -C) work identically, long options and advanced flags (like --exclude-vcs or --transform) may differ.
On Alpine Linux, default BusyBox tar supports standard options (-c, -x, -t, -z, -j, -C) but lacks advanced GNU extensions like --wildcards, --xattrs, and complex exclude rules. For full feature parity on Alpine containers, run apk add --no-cache tar.
Troubleshooting Common Errors and Diagnostics
tar: Removing leading '/' from member names
Root Cause: This is an informational safety warning, not an error. GNU tar automatically strips leading slashes from absolute paths so the archive can be safely extracted anywhere.
Resolution: No fix needed; this is standard safe behavior. To restore to root, use -C / during extraction.
tar -xzvf backup.tar.gz -C /
tar: file changed as we read it
Root Cause: A file being archived (such as an active database log or socket) was modified by another process while tar was reading it.
Resolution: Stop active writer daemons before archiving, or pass --warning=no-file-changed in automated backup scripts.
tar --warning=no-file-changed -czvf backup.tar.gz /var/log/
tar: /dev/tape: Cannot open: No such file or directory
Root Cause: The -f option was omitted. When -f is missing, tar defaults to reading from or writing to the system tape drive device.
Resolution: Always include -f followed by the archive filename.
tar -czvf myarchive.tar.gz myfolder/
Alternatives, Related Commands, and Related Tutorials
- gzip Command in Linux: Compress and Decompress Files with Deflate — Practical syntax, flags, and examples for
gzip. - How to Unzip a .gz File in Linux: gunzip, gzip -d, and zcat Guide — Practical syntax, flags, and examples for
gzip. - gunzip Command in Linux: Decompress Gzip Files and Data Streams — Practical syntax, flags, and examples for
gunzip. - xargs Command in Linux: Build and Execute Command Lines from Stdin — Practical syntax, flags, and examples for
xargs. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides

Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!