tar Command in Linux: Syntax, Options & Practical Examples

Deepak Prasad
Tested on Ubuntu 25.04 (Plucky Puffin)
Package tar (GNU tar) 1.35
Applies to Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Oracle Linux, CentOS Stream, Fedora, Arch Linux, SUSE, openSUSE, Alpine
macOS
Privilege sudo or root
Man page tar(1)
Scope GNU tar bundles files and directories into a single archive and restores them later. Create with -c, list with -t, extract with -x, and add gzip, bzip2, xz, or zstd compression with -z, -j, -J, or -a.
Related guides gzip
Linux commands

tar — quick reference

Main operation mode

Pick exactly one primary action per invocation — create, list, extract, append, compare, or delete members.

When to use Command
Create a new archive from files or directories tar -cf archive.tar files…
Long form of create tar --create -f archive.tar files…
List archive members without extracting tar -tf archive.tar
Long form of list tar --list -f archive.tar
Extract all members from an archive tar -xf archive.tar
Long form of extract tar --extract -f archive.tar
Synonym for extract (--get) tar --get -f archive.tar
Append files to the end of an existing archive tar -rf archive.tar newfiles…
Long form of append tar --append -f archive.tar newfiles…
Append only files newer than copies already in the archive tar -uf archive.tar files…
Long form of update tar --update -f archive.tar files…
Compare archive members to files on disk tar -df archive.tar files…
Long form of compare tar --compare -f archive.tar files…
Synonym for compare (--diff) tar --diff -f archive.tar files…
Remove named members from an archive (not on tape devices) tar --delete -f archive.tar members…
Concatenate other tar archives into one tar -Af dest.tar other.tar
Long form of concatenate tar --catenate -f dest.tar other.tar
Synonym for concatenate (--concatenate) tar --concatenate -f dest.tar other.tar
Test the volume label and exit tar --test-label -f archive.tar

Operation modifiers

Fine-tune incremental backups, sparse files, and tape-oriented behavior.

When to use Command
Check device numbers when creating incremental archives (default) tar --check-device -cf archive.tar dir/
Skip device-number checks for incremental archives tar --no-check-device -cf archive.tar dir/
GNU incremental snapshot (new format) tar -g snapshot.snar -cf archive.tar dir/
Long form of listed incremental tar --listed-incremental=snapshot.snar -cf archive.tar dir/
Old GNU incremental backup format tar -G -cf archive.tar dir/
Long form of old incremental tar --incremental -cf archive.tar dir/
Dump level for listed-incremental archives tar --level=1 -g snap.snar -cf archive.tar dir/
Select hole-detection technique when archiving tar --hole-detection=seek -cf archive.tar file
Do not exit with failure on unreadable files tar --ignore-failed-read -cf archive.tar dir/
Mark archive as not seekable tar --no-seek -cf archive.tar dir/
Mark archive as seekable tar --seek -cf archive.tar dir/
Store sparse files efficiently tar -S -cf archive.tar bigfile
Long form of sparse tar --sparse -cf archive.tar bigfile
Set sparse format version (implies --sparse) tar --sparse-version=1.0 -cf archive.tar file
Process only the Nth archive occurrence of a member tar --occurrence=1 -tf archive.tar member

Local file name selection

Control which paths enter or leave the archive and how directories are walked.

When to use Command
Add a file whose name starts with - tar --add-file=./-file -cf archive.tar
Change directory before create/extract operations tar -cf archive.tar -C /path/to/dir .
Long form of directory change tar --directory=/path/to/dir -cf archive.tar .
Exclude members matching a shell pattern tar --exclude='*.tmp' -cf archive.tar dir/
Exclude backup and lock files tar --exclude-backups -cf archive.tar dir/
Skip cache directory contents (respect CACHEDIR.TAG) tar --exclude-caches -cf archive.tar dir/
Exclude entire cache-tagged directories tar --exclude-caches-all -cf archive.tar dir/
Exclude everything under cache-tagged directories tar --exclude-caches-under -cf archive.tar dir/
Read per-directory exclude patterns from a file tar --exclude-ignore=.tarignore -cf archive.tar dir/
Recursive exclude-ignore for subdirectories tar --exclude-ignore-recursive=.tarignore -cf archive.tar dir/
Exclude contents of tag-file directories (keep the tag) tar --exclude-tag=TAG -cf archive.tar dir/
Exclude directories that contain a tag file tar --exclude-tag-all=TAG -cf archive.tar dir/
Exclude all files under tag-file directories tar --exclude-tag-under=TAG -cf archive.tar dir/
Skip version-control directories (.git, etc.) tar --exclude-vcs -cf archive.tar dir/
Read VCS ignore files for exclude patterns tar --exclude-vcs-ignores -cf archive.tar dir/
Read exclude patterns from a file tar -X patterns.txt -cf archive.tar dir/
Long form of exclude-from tar --exclude-from=patterns.txt -cf archive.tar dir/
Read member names to extract or create from a file tar -T list.txt -cf archive.tar
Long form of files-from tar --files-from=list.txt -cf archive.tar
Do not descend into subdirectories automatically tar --no-recursion -cf archive.tar dir/
Recurse into directories (default) tar --recursion -cf archive.tar dir/
Read null-terminated names from -T (implies verbatim) tar --null -T list.txt -cf archive.tar
Disable effect of a previous --null tar --no-null -T list.txt -cf archive.tar
Do not unquote names from -T tar --no-unquote -T list.txt -cf archive.tar
Unquote names from -T (default) tar --unquote -T list.txt -cf archive.tar
Treat -T names verbatim (no option parsing) tar --verbatim-files-from -T list.txt -cf archive.tar
-T treats leading-dash names as options (default) tar --no-verbatim-files-from -T list.txt -cf archive.tar

File name matching options

Affect how --exclude and related patterns match paths.

When to use Command
Patterns must match from the start of the file name tar --anchored --exclude='foo*' -cf archive.tar dir/
Patterns may match after any / (default for exclusion) tar --no-anchored --exclude='*.tmp' -cf archive.tar dir/
Case-insensitive pattern matching tar --ignore-case --exclude='*.TXT' -cf archive.tar dir/
Case-sensitive matching (default) tar --no-ignore-case --exclude='*.txt' -cf archive.tar dir/
Use wildcards in exclude patterns (default) tar --wildcards --exclude='*.o' -cf archive.tar dir/
Literal string matching (no globbing) tar --no-wildcards --exclude='*.o' -cf archive.tar dir/
Wildcards do not match / tar --no-wildcards-match-slash --exclude='*' -cf archive.tar dir/
Wildcards may match / (default for exclusion) tar --wildcards-match-slash --exclude='*' -cf archive.tar dir/

Overwrite control

Decide what happens when extracted files already exist on disk.

When to use Command
Keep existing files; treat conflicts as errors tar -k -xf archive.tar
Long form of keep-old-files tar --keep-old-files -xf archive.tar
Skip existing files silently tar --skip-old-files -xf archive.tar
Overwrite existing files when extracting tar --overwrite -xf archive.tar
Keep on-disk file if it is newer than the archive copy tar --keep-newer-files -xf archive.tar
Remove each file before extracting over it tar -U -xf archive.tar
Long form of unlink-first tar --unlink-first -xf archive.tar
Extract into a new subdirectory (avoid loose files) tar --one-top-level=bundle -xf archive.tar
Preserve symlinks to directories on extract tar --keep-directory-symlink -xf archive.tar
Preserve existing directory metadata on extract tar --no-overwrite-dir -xf archive.tar
Overwrite directory metadata on extract (default) tar --overwrite-dir -xf archive.tar
Empty target directories before extracting into them tar --recursive-unlink -xf archive.tar
Delete files from disk after adding them to the archive tar --remove-files -cf archive.tar files…
Verify archive contents after writing tar -W -cf archive.tar dir/
Long form of verify tar --verify -cf archive.tar dir/

Select output stream

Send extracted data to stdout or external commands instead of files.

When to use Command
Extract files to standard output tar -O -xf archive.tar member
Long form of to-stdout tar --to-stdout -xf archive.tar member
Pipe each extracted file to a shell command tar --to-command='cat > /tmp/out' -xf archive.tar
Ignore non-zero exit codes from --to-command children tar --ignore-command-error --to-command='cmd' -xf archive.tar
Treat non-zero child exit codes as errors (default) tar --no-ignore-command-error --to-command='cmd' -xf archive.tar

Handling of file attributes

Preserve or override owners, modes, and timestamps.

When to use Command
Extract permission bits (default for root) tar -p -xf archive.tar
Long form (--preserve-permissions, --same-permissions) tar --preserve-permissions -xf archive.tar
Try to restore ownership from the archive (default for root) tar --same-owner -xf archive.tar
Extract files as the current user tar --no-same-owner -xf archive.tar
Apply the user's umask to extracted permissions tar --no-same-permissions -xf archive.tar
Show numeric UID/GID in listings tar --numeric-owner -tvf archive.tar
Force owner name on added files tar --owner=USER -cf archive.tar files…
Force group name on added files tar --group=GROUP -cf archive.tar files…
Map owners from a file tar --owner-map=map.txt -cf archive.tar dir/
Map groups from a file tar --group-map=map.txt -cf archive.tar dir/
Force symbolic mode on added files tar --mode=u=rw,go=r -cf archive.tar files…
Set mtime on added files from a date or file tar --mtime='2024-01-01' -cf archive.tar files…
Only set mtime when file is newer than --mtime value tar --clamp-mtime --mtime='2024-01-01' -cf archive.tar files…
Do not restore modification times on extract tar -m -xf archive.tar
Long form of touch tar --touch -xf archive.tar
Preserve access times on archived files tar --atime-preserve -cf archive.tar dir/
Delay directory mtime/permission restore until extract ends tar --delay-directory-restore -xf archive.tar
Cancel --delay-directory-restore tar --no-delay-directory-restore -xf archive.tar
Sort directory entries when creating (none, name, inode) tar --sort=name -cf archive.tar dir/
Store command-line members in the order given tar -s -cf archive.tar a b
Long form of preserve-order (--same-order) tar --preserve-order -cf archive.tar a b

Handling of extended file attributes

POSIX ACLs, extended attributes, and SELinux contexts.

When to use Command
Store and restore POSIX ACLs tar --acls -cf archive.tar dir/
Disable ACL support tar --no-acls -cf archive.tar dir/
Store and restore extended attributes tar --xattrs -cf archive.tar dir/
Disable extended attribute support tar --no-xattrs -cf archive.tar dir/
Include only xattr keys matching a mask tar --xattrs-include='user.*' -cf archive.tar dir/
Exclude xattr keys matching a mask tar --xattrs-exclude='user.*' -cf archive.tar dir/
Store and restore SELinux contexts tar --selinux -cf archive.tar dir/
Disable SELinux context support tar --no-selinux -cf archive.tar dir/

Device selection and switching

Point tar at archive files, tapes, or remote devices.

When to use Command
Read or write a specific archive file (- = stdout) tar -cf archive.tar files…
Long form of file tar --file=archive.tar -cf files…
Treat archive path as local even if it contains : tar --force-local -tf ./host:backup.tar
Multi-volume archive operations tar -M -tf archive.tar
Long form of multi-volume tar --multi-volume -tf archive.tar
Change tape volume after N KiB tar -L 1024 -cf archive.tar dir/
Long form of tape-length tar --tape-length=1024 -cf archive.tar dir/
Run script at end of each volume tar -F script.sh -cf archive.tar dir/
Long form (--info-script, --new-volume-script) tar --info-script=script.sh -cf archive.tar dir/
Track volume number in a file tar --volno-file=volno.txt -cf archive.tar dir/
Custom remote rmt command tar --rmt-command=/usr/sbin/rmt -cf archive.tar dir/
Custom remote shell command tar --rsh-command=/usr/bin/ssh -cf host:archive.tar dir/

Device blocking

Tape block sizing and end-of-archive detection.

When to use Command
Set blocking factor (records × 512 bytes) tar -b 20 -cf archive.tar dir/
Long form of blocking-factor tar --blocking-factor=20 -cf archive.tar dir/
Reblock while reading (4.2BSD pipes) tar -B -cf archive.tar dir/
Long form of read-full-records tar --read-full-records -cf archive.tar dir/
Treat zeroed blocks as EOF tar -i -tf archive.tar
Long form of ignore-zeros tar --ignore-zeros -tf archive.tar
Set record size in bytes (multiple of 512) tar --record-size=10240 -cf archive.tar dir/

Archive format selection

Choose ustar, pax, GNU, or legacy V7 layout.

When to use Command
GNU tar format (default on Ubuntu 25.04) tar --format=gnu -cf archive.tar dir/
POSIX pax format tar --format=pax -cf archive.tar dir/
Synonym for pax tar --format=posix -cf archive.tar dir/
POSIX ustar format tar --format=ustar -cf archive.tar dir/
Old V7 tar format tar --format=v7 -cf archive.tar dir/
Legacy GNU format (tar ≤ 1.12) tar --format=oldgnu -cf archive.tar dir/
Same as --format=v7 tar --old-archive -cf archive.tar dir/
Portability alias for V7 tar --portability -cf archive.tar dir/
Same as --format=posix tar --posix -cf archive.tar dir/
Control pax extended-header keywords tar --pax-option=delete=atime -cf archive.tar dir/
Set volume label (glob when listing/extracting) tar -V 'LABEL' -cf archive.tar dir/
Long form of label tar --label='LABEL' -cf archive.tar dir/

Compression options

Filter the archive through gzip, bzip2, xz, zstd, or a custom program.

When to use Command
gzip compress while creating (.tar.gz, .tgz) tar -czf archive.tar.gz dir/
Long form (--gzip, --gunzip, --ungzip) tar --gzip -cf archive.tar.gz dir/
bzip2 compress while creating (.tar.bz2) tar -cjf archive.tar.bz2 dir/
Long form of bzip2 tar --bzip2 -cf archive.tar.bz2 dir/
xz compress while creating (.tar.xz) tar -cJf archive.tar.xz dir/
Long form of xz (--lzma is an alias) tar --xz -cf archive.tar.xz dir/
zstd compress while creating (.tar.zst) tar --zstd -cf archive.tar.zst dir/
Pick compressor from the archive suffix tar -caf archive.tar.zst dir/
Long form of auto-compress tar --auto-compress -cf archive.tar.zst dir/
Do not infer compressor from suffix tar --no-auto-compress -cf archive.tar dir/
lzip compression (needs lzip on PATH) tar --lzip -cf archive.tar.lz dir/
lzop compression (needs lzop on PATH) tar --lzop -cf archive.tar.lzo dir/
Legacy compress compression (.Z) tar -Zcf archive.tar.Z dir/
Long form (--compress, --uncompress) tar --compress -cf archive.tar.Z dir/
Custom compress/decompress program tar -I 'gzip -9' -cf archive.tar.gz dir/
Long form of use-compress-program tar --use-compress-program='gzip -9' -cf archive.tar.gz dir/

Local file selection (paths and time)

Dereference links, anchor paths, and filter by modification time.

When to use Command
Follow symlinks; archive the target file tar -h -cf archive.tar link
Long form of dereference tar --dereference -cf archive.tar link
Follow hard links and archive referred files tar --hard-dereference -cf archive.tar link
Store absolute paths (do not strip leading /) tar -P -cf archive.tar /etc/hostname
Long form of absolute-names tar --absolute-names -cf archive.tar /etc/hostname
Stay on one file system when creating tar --one-file-system -cf archive.tar /
Archive only files newer than a date or reference file tar -N '2024-01-01' -cf archive.tar dir/
Long form (--newer, --after-date) tar --newer='2024-01-01' -cf archive.tar dir/
Compare only data modification time (not status) tar --newer-mtime='2024-01-01' -cf archive.tar dir/
Begin reading the archive at a member tar -K member -tf archive.tar
Long form of starting-file tar --starting-file=member -tf archive.tar
Backup files before removal (--remove-files, extract) tar --backup=numbered --remove-files -cf archive.tar files…
Override backup suffix (default ~) tar --suffix=.bak --backup=simple -cf archive.tar files…

File name transformations

Rename members on extract or create with sed-style expressions.

When to use Command
Strip leading path components on extract tar --strip-components=1 -xf archive.tar
sed-style rename (s/old/new/) on store or extract tar --transform='s/old/new/' -cf archive.tar dir/
Short alias for transform tar --xform='s/old/new/' -cf archive.tar dir/

Informative output

Verbosity, progress, and debugging aids.

When to use Command
List processed files verbosely tar -cvf archive.tar dir/
Long form of verbose tar --verbose -cf archive.tar dir/
Verbose list with block numbers tar -R -tf archive.tar
Long form of block-number tar --block-number -tf archive.tar
Print modification times in UTC tar --utc -tvf archive.tar
Print timestamps at full resolution tar --full-time -tvf archive.tar
Warn when not all hard links are dumped tar -l -cf archive.tar dir/
Long form of check-links tar --check-links -cf archive.tar dir/
Print byte totals after processing tar --totals -cf archive.tar dir/
Print totals when a signal arrives tar --totals=SIGUSR1 -cf archive.tar dir/
Progress message every N records tar --checkpoint=100 -cf archive.tar dir/
Run an action at each checkpoint tar --checkpoint-action=echo=%u -cf archive.tar dir/
Send verbose listing to a file tar --index-file=listing.txt -tvf archive.tar
Show tar compile-time defaults tar --show-defaults
List directories omitted by search criteria tar --show-omitted-dirs -tf archive.tar pattern
Show valid snapshot-file field ranges tar --show-snapshot-field-ranges
Show names after --transform tar --show-transformed-names -cf archive.tar dir/
Synonym (--show-stored-names) tar --show-stored-names -cf archive.tar dir/
Control warning keywords tar --warning=no-all -cf archive.tar dir/
Set name quoting style for list output tar --quoting-style=literal -tvf archive.tar
Additionally quote characters in listings tar --quote-chars='$' -tvf archive.tar
Disable quoting for characters tar --no-quote-chars='$' -tvf archive.tar
Ask for confirmation for each action tar -w --delete -f archive.tar member
Long form (--interactive, --confirmation) tar --interactive --delete -f archive.tar member

Compatibility and other options

Legacy shortcuts and built-in help.

When to use Command
Creating: same as --old-archive; extracting: same as --no-same-owner tar -o -cf archive.tar dir/
Show full help tar --help
Short help tar -?
Short usage summary tar --usage
Print program version tar --version
Disable potentially harmful options tar --restrict -cf archive.tar dir/

tar — command syntax

GNU tar combines one main mode (-c, -t, -x, …) with modifiers and -f to name the archive. Synopsis from tar --help on Ubuntu 25.04 (GNU tar 1.35):

text
tar [OPTION...] [FILE]...

Examples printed by --help:

text
tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.
tar -tvf archive.tar         # List all files in archive.tar verbosely.
tar -xf archive.tar          # Extract all files from archive.tar.

Default output often includes --format=gnu -f- -b20 --quoting-style=escape. tar does not create an empty archive — you must name at least one file or directory to store.


tar — command examples

Essential Create an archive and list members without extracting

The everyday backup flow: pack files into a .tar, then confirm what was stored before you move or delete the originals.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab
mkdir -p "$WORKDIR"/src && cd "$WORKDIR"
echo 'file one' > src/${PREFIX}one.txt
echo 'file two' > src/${PREFIX}two.txt
tar -cvf ${PREFIX}archive.tar -C src ${PREFIX}one.txt ${PREFIX}two.txt
tar -tf ${PREFIX}archive.tar

Sample output from tar -cvf:

text
tcs_tar_one.txt
tcs_tar_two.txt

Sample output from tar -tf:

text
tcs_tar_one.txt
tcs_tar_two.txt

-C src changes to the source directory so members are stored without the full /tmp/... path. -t lists names only; add -v for sizes and modes (tar -tvf).

Essential Extract everything or pick specific members

Extract restores files relative to your current directory unless you pass -C.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab
mkdir -p "$WORKDIR"/extract && cd "$WORKDIR"
tar -xf ${PREFIX}archive.tar -C extract/
ls extract/
tar -xf ${PREFIX}archive.tar -C extract/ ${PREFIX}two.txt
ls -l extract/

Sample output:

output
tcs_tar_one.txt
tcs_tar_two.txt
total 8
-rw-r--r-- 1 root root 9 Jul  1 14:18 tcs_tar_one.txt
-rw-r--r-- 1 root root 9 Jul  1 14:18 tcs_tar_two.txt

Listing members on the second extract overwrites ${PREFIX}two.txt again; omit member names to unpack the whole archive.

Essential Create and list a gzip-compressed .tar.gz

-z pipes the archive through gzip. Use the .tar.gz or .tgz suffix so future you knows which extractor to run.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab && cd "$WORKDIR"
tar -czf ${PREFIX}archive.tar.gz -C src ${PREFIX}one.txt ${PREFIX}two.txt
tar -tzf ${PREFIX}archive.tar.gz

Sample output:

output
tcs_tar_one.txt
tcs_tar_two.txt

Extract later with tar -xzf ${PREFIX}archive.tar.gz. For bzip2 use -j (.tar.bz2); for xz use -J (.tar.xz).

Common Exclude patterns while creating an archive

--exclude accepts glob patterns. Order matters — later rules do not undo earlier inclusions.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab && cd "$WORKDIR"
echo 'file three' > src/${PREFIX}three.txt
tar -cf ${PREFIX}excl.tar -C src --exclude='*two*' ${PREFIX}one.txt ${PREFIX}two.txt ${PREFIX}three.txt
tar -tf ${PREFIX}excl.tar

Sample output:

output
tcs_tar_one.txt
tcs_tar_three.txt

${PREFIX}two.txt was skipped because its name matches *two*. For many rules, put patterns in a file and pass -X patterns.txt.

Common Extract into another directory with -C

-C changes directory before extract, so you do not clutter the current working tree.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab
mkdir -p "$WORKDIR"/dest && cd "$WORKDIR"
tar -xf ${PREFIX}archive.tar -C dest/
find dest -type f

Sample output:

output
dest/tcs_tar_one.txt
dest/tcs_tar_two.txt

Combine with --strip-components=N when the archive stores deep paths you want to trim — see tar --strip-components and zip --junk-paths.

Common Append (-r) vs update (-u) members

-r always appends new bytes at the end. -u only adds files that are newer than copies already stored.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab && cd "$WORKDIR"
echo 'new file' > src/${PREFIX}new.txt
tar -rf ${PREFIX}archive.tar -C src ${PREFIX}new.txt
tar -tf ${PREFIX}archive.tar
echo 'updated' > src/${PREFIX}new.txt
tar -uf ${PREFIX}archive.tar -C src ${PREFIX}new.txt
tar -tvf ${PREFIX}archive.tar | grep new

Sample output:

output
tcs_tar_one.txt
tcs_tar_two.txt
tcs_tar_new.txt
-rw-r--r-- root/root         8 2026-07-01 14:18 tcs_tar_new.txt

GNU tar keeps older member copies inside the archive when you update — the listing may show duplicates until you repack. For clean trees, create a fresh archive instead of repeated -u.

Common Compare archive members to files on disk (-d)

-d reports size or metadata differences without extracting — useful before overwriting production configs.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab && cd "$WORKDIR"
echo 'changed' > src/${PREFIX}two.txt
tar -df ${PREFIX}archive.tar -C src ${PREFIX}two.txt

Sample output:

output
tcs_tar_two.txt: Size differs

When files match, tar prints nothing and exits 0.

Advanced Merge archives (-A) and delete members (--delete)

-A appends another tar file's contents. --delete removes members from an archive file (not tape devices).

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab && cd "$WORKDIR"
tar -cf ${PREFIX}arch2.tar -C src ${PREFIX}three.txt
tar -Af ${PREFIX}archive.tar ${PREFIX}arch2.tar
tar --delete -f ${PREFIX}archive.tar ${PREFIX}one.txt
tar -tf ${PREFIX}archive.tar

Sample output:

output
tcs_tar_two.txt
tcs_tar_new.txt
tcs_tar_three.txt

--delete rewrites the archive in place — keep a backup copy when the archive is irreplaceable.

Advanced Auto-detect compression from the file suffix (-a)

-a picks gzip, bzip2, xz, or zstd from the extension — handy in scripts when the suffix is the contract.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab && cd "$WORKDIR"
tar -caf ${PREFIX}auto.tar.zst -C src ${PREFIX}one.txt
tar -tf ${PREFIX}auto.tar.zst

Sample output:

output
tcs_tar_one.txt

Install zstd if -caf fails with "Cannot exec". The same -a flag works with .tar.gz, .tar.bz2, and .tar.xz suffixes.

Advanced Rename on store (--transform) and strip path components

Transform applies a sed expression to member names. --strip-components trims leading directories on extract.

Run the commands:

bash
PREFIX=tcs_tar_
WORKDIR=/tmp/${PREFIX}lab
mkdir -p "$WORKDIR"/xdest && cd "$WORKDIR"
tar --transform='s/tcs_tar_/renamed_/' -cf ${PREFIX}xform.tar -C src ${PREFIX}two.txt
tar -tf ${PREFIX}xform.tar
tar --strip-components=0 -xf ${PREFIX}xform.tar -C xdest/
ls xdest/

Sample output:

output
renamed_two.txt
renamed_two.txt

Use --show-transformed-names while creating to preview stored paths before you extract on a production host.


tar — when to use / when not

Use tar when Use something else when
  • You need a portable bundle of many files for backup, transfer, or software distribution
  • You want compression plus archiving in one step (.tar.gz, .tar.xz, .tar.zst)
  • You must preserve Unix metadata (owners, permissions, symlinks) across hosts
  • You are unpacking upstream release tarballs or building Debian/RPM source packages
  • You want incremental or merged archives on a single GNU tar host
  • You only need to compress one filebzip2 or xz alone
  • You are syncing live directories repeatedly → rsync
  • You need a Windows-friendly zip archive → zip
  • You are reading cpio initramfs images → cpio
  • You are on macOS BSD tar and scripts assume GNU flags → install GNU tar or adjust flags

tar vs zip

GNU tar zip
Typical extensions .tar, .tar.gz, .tar.xz, .tar.zst .zip
Strength Preserves Unix ownership, symlinks, and pax metadata Cross-platform; common on Windows
Compression External filters (gzip, xz, zstd, …) Built-in per-member compression
Random access Sequential; list/extract by name Better random access to single members
Best for Linux backups, release tarballs, package sources Sharing archives with non-Unix systems

See How to zip a folder in Linux when zip is the better fit.


tar — interview corner

What is the tar command used for in Linux?

tar (tape archive) collects many files and directories into one archive file and can restore them later. Modern use is almost always disk files, not tapes.

The three modes interviewers expect:

Flag Action
-c Create an archive
-t List contents
-x eXtract contents

-f archive.tar names the archive file and almost always appears with those letters (-cf, -tf, -xf). Compression flags like -z (gzip) wrap the archive stream.

A strong answer is:

"tar bundles files into a single archive and extracts them later. I use tar -cf to create, tar -tf to list, tar -xf to extract, and -z/-j/-J when I need gzip, bzip2, or xz compression in the same step."

How do you create and extract a .tar.gz file?

Add -z to filter through gzip. The f must stay attached to the archive name.

Create:

bash
tar -czf backup.tar.gz /etc/nginx

List:

bash
tar -tzf backup.tar.gz

Extract:

bash
tar -xzf backup.tar.gz

-a on GNU tar can pick the compressor from the suffix (for example .tar.zst).

A strong answer is:

"tar -czf creates a gzip tarball, tar -tzf lists it, tar -xzf extracts it. The f flag must sit next to the filename — I treat zcf, xzf, and tzf as fixed patterns."

What does tar -C do?

-C DIR changes to DIR before tar reads or writes files. It solves two common problems:

  1. Create without storing absolute paths: tar -cf arc.tar -C /var/www .
  2. Extract into a target tree: tar -xf arc.tar -C /opt/restore

Without -C, extracted files land relative to your current working directory.

A strong answer is:

"tar -C changes directory before add or extract operations. I use it to pack a folder's contents without the full path prefix, or to unpack into a specific destination directory."

How do you exclude files when creating a tar archive?

Pass one or more --exclude=PATTERN options. Globs match member paths as tar walks directories.

bash
tar -czf site.tar.gz --exclude='*.log' --exclude='node_modules' /var/www

For long lists, put patterns in a file and use -X patterns.txt. The same --exclude flag works on extract to skip members during unpack.

A strong answer is:

"I pass --exclude globs on the command line or use -X with a pattern file. The same exclude syntax works when extracting if I need to skip paths during unpack."

When would you choose tar over rsync?

tar builds a single portable blob you can copy once, store on object storage, or attach to a ticket. Metadata travels inside the archive.

rsync synchronizes live directories — great for repeated incremental updates, poor when you need one frozen artifact.

Choose tar for release artifacts, offline backups, and crossing air gaps. Choose rsync for mirroring /var/www to a standby server every hour.

A strong answer is:

"tar gives me one self-contained archive I can store or ship; rsync keeps directories in sync incrementally. I tarball for releases and cold backups; rsync for ongoing replication."


Troubleshooting

Symptom Likely cause Fix
tar: archive.tar: Cannot open: No such file or directory Wrong path or missing -f Check the archive path; keep f adjacent to the filename (-xvf)
Cannot exec: gzip: No such file or directory Compressor not installed sudo apt install gzip (or zstd, xz, … for other flags)
Unexpected EOF in archive Truncated download or corrupt file Re-download; verify with tar -tf before deleting sources
Not found in archive Typo in member name List exact names with tar -tf archive.tar
Extracted files land in the wrong place Missing -C or unexpected path prefixes Use -C dest/ or --strip-components=N
Cannot open: Permission denied on create of /path Insufficient rights Run with sudo or archive a directory you own
Unknown option on macOS BSD tar vs GNU tar flags Install GNU tar (brew install gnu-tar) or adjust flags
Duplicate members after -u GNU tar appends updated copies Repack with a fresh tar -cf for a clean archive
lzip / lzop / compress not found Optional compressor missing Install the tool or pick -z, -j, -J, or --zstd instead

Rohan Timalsina

is a technical writer and Linux enthusiast who writes practical guides on Linux commands and system administration. He focuses on simplifying complex topics through clear explanations.

  • Linux
  • HTML5
  • JavaScript
  • Web Design
  • Front-end Web Development