Put two files into one archive
tar collects files into an archive: a sequence of named members containing file data and metadata such as type, permissions, and modification time. It is useful for a service handoff or a controlled backup. It is a standalone program, not a shell built-in. Creating an archive is not the same operation as compressing it, and extracting one asks the filesystem to act on the stored names.
We will package a synthetic service configuration, inspect it, and restore it into new directories. These examples use GNU tar 1.35, Bash 5.2.21, and gzip 1.12 on Linux. Use an ordinary account in a directory you control. No command needs elevated privileges. If tar-lab already exists, choose another name. The setup changes into that new directory and all later examples stay there; stop if setup fails.
mkdir creates directories; -m 700 gives tar-lab owner-only access. cd changes the shell's working directory. Every setup command is connected with &&, which runs the next command only after success. The shell's > creates or replaces a file. printf's fixed %s\n format prints each supplied string followed by a newline; single quotes keep the format and data intact. The printf article explains why the data should not become the format.
chmod 640 sets app.conf to owner read/write, group read, and no permissions for others before we archive it.
tar -c creates an archive. -f takes the archive filename as its next argument: handoff.tar is the output, not a source to include. The remaining operands name two input files. Then -t lists the archive rather than creating or extracting it; the same -f now names the input archive.
mkdir -m 700 tar-lab &&
cd tar-lab &&
mkdir release &&
printf '%s\n' 'listen=127.0.0.1' 'debug=false' > release/app.conf &&
printf '%s\n' 'Service handoff: synthetic fixture.' > release/README &&
chmod 640 release/app.conf &&
tar -c -f handoff.tar release/app.conf release/README &&
tar -t -f handoff.tarrelease/app.conf
release/READMECreation normally prints nothing; the two lines come from listing. The originals still exist. The archive is outside release, so archiving that directory later cannot accidentally include the archive being written. A directory operand would recursively include its contents; our explicit two-file selection makes member order predictable.
Read the option style before moving a letter
These three commands list the same two members. The first spells each short option separately. The second combines them after one dash: -tf means -t followed by -f, whose archive argument follows the cluster. The third uses tar's traditional option style: its first argument is an undashed group of option letters, and arguments for letters that need them follow the whole group in letter order.
The absence of a dash is not cosmetic. In the traditional group cfz, z requests gzip compression, which we will use below. As the GNU manual's Old Option Style section explains, cfz gives f its archive argument after the group, whereas -cfz gives f the attached argument z: that final letter is consumed as the filename, not interpreted as a compression option. That typo can select an unintended output file. Do not test it in a directory containing valuable data. Keeping argument-taking options separate is a readable default.
Long GNU spellings are --create, --list, --extract, and --file=NAME. The equals sign attaches the archive argument to --file. Choose one primary operation per invocation; creation, listing, and extraction are different jobs, not switches to stack together.
tar -t -f handoff.tar
tar -tf handoff.tar
tar tf handoff.tarrelease/app.conf
release/README
release/app.conf
release/README
release/app.conf
release/READMEChoose the names that travel
The archive records member names, not the original shell's working directory. Our first archive carries release/app.conf. To ship app.conf at the top level instead, use -C release before the input names. -C changes tar's working directory for subsequent file operands; it does not change your shell's directory.
The archive filename supplied to -f remains relative to tar's original working directory, even when -C precedes it. Here flat.tar is created beside handoff.tar, not inside release. The GNU manual's Changing the Working Directory section documents this important distinction.
This creates another archive without changing the source files. Explicit names again give a predictable two-member list.
tar -c -f flat.tar -C release app.conf README &&
tar -t -f flat.tarapp.conf
READMEExtracting handoff.tar will recreate the release prefix. Extracting flat.tar will not. A suffix such as .tar does not add or remove a directory level. Inspect the actual member names before deciding where a restore should land.
Restore into an empty destination
-x extracts members, creating files and intermediate directories as needed. Without a member selection, it processes the archive's members. -C restored makes their relative paths start inside restored, which must already exist. The command below creates that new destination and writes only there.
GNU --no-same-owner tells extraction not to restore archived ownership. --no-same-permissions applies the current file-creation permission mask instead of restoring all recorded mode bits unchanged. These are ordinary-user defaults, but naming them makes this inspection restore's policy explicit. Neither option makes privileged extraction advisable.
cat prints the known text file after extraction succeeds. It is appropriate here because we supplied its bytes; do not automatically print the raw contents of an unfamiliar archive to your terminal.
mkdir -m 700 restored &&
tar -x -f handoff.tar -C restored --no-same-owner --no-same-permissions &&
cat restored/release/app.conflisten=127.0.0.1
debug=falseThe release directory appears beneath restored because it is part of each stored name. Running the same extraction in a working project can overwrite files; creating a genuinely new destination avoids that collision in this fixture. -C is a destination choice, not a general security sandbox.
Read one member without restoring a tree
If the immediate task is reviewing a supplied configuration, extraction need not create its pathname. GNU -O sends extracted file contents to standard output instead. Select the exact stored name, release/app.conf, after the archive option. app.conf alone would not match this archive.
This command reads handoff.tar and prints only the two known configuration lines. It does not create release/app.conf from the archive or change the existing copy. Multiple selected regular-file members would have their contents concatenated, without a separator or filename label, so keep this inspection to one known member.
tar -x -O -f handoff.tar release/app.conflisten=127.0.0.1
debug=falseThis is useful during an authorized review of a supplied artifact, but stdout is still a byte stream. Unknown content can include terminal control bytes or secrets. Route unfamiliar bytes to an appropriate inspector or protected review file rather than treating -O as sanitization. Keep the original archive and its provenance.
Compression wraps the archive
-z asks GNU tar to pass the archive through gzip. The first command writes handoff.tar.gz; it does not replace handoff.tar. The .gz suffix describes that choice, but merely naming an output file .gz would not enable compression. GNU -a is a separate option that selects compression from a filename suffix; we do not need it when -z is explicit.
On a regular archive file, GNU tar recognizes supported compression from its signature and can list it without -z. A pipe is different: specify -z when feeding this gzip stream through standard input. In -f -, the dash means standard input for listing, or standard output for creation. It is the archive stream, not a list of input filenames.
cat copies the compressed file to the pipe; | connects that output to tar's input. These two listing commands therefore inspect the same member sequence through different transport paths. gzip must be installed for these examples.
tar -c -z -f handoff.tar.gz release/app.conf release/README &&
tar -t -f handoff.tar.gz &&
cat handoff.tar.gz | tar -t -z -f -release/app.conf
release/README
release/app.conf
release/READMEGNU tar's compression chapter documents automatic regular-file recognition and the explicit decompressor needed for pipes. Compression does not change member paths or restore permissions. It also changes update choices: GNU tar cannot append members directly to a compressed archive. For this handoff, rebuilding a fresh archive is clearer than mutating it.
Ask what verification actually verifies
A successful listing means tar could read the archive structure it traversed. It does not compare every stored byte with its original file, authenticate the sender, or prove that a live application's files formed a consistent snapshot.
gzip -t tests the compressed stream's integrity without extracting it to disk. That is gzip's -t, not tar's listing operation. GNU tar -d instead compares archived members against same-named files on the filesystem, reporting differences such as content, size, mode, ownership, and modification time. Here handoff.tar uses release-prefixed names, and we are still in tar-lab, so comparison reaches the original release files.
The first two checks should succeed silently. We then change only app.conf's permissions from 640 to 600—removing group read—and compare again. $? is Bash's status of the immediately preceding command; capture it before running another command. The final chmod restores the original mode for subsequent examples.
gzip -t handoff.tar.gz
printf 'gzip status=%s\n' "$?"
tar -d -f handoff.tar
printf 'compare status=%s\n' "$?"
chmod 600 release/app.conf &&
tar -d -f handoff.tar
printf 'changed status=%s\n' "$?"
chmod 640 release/app.confgzip status=0
compare status=0
release/app.conf: Mode differs
changed status=1GNU tar comparison returns 1 for differences. It ignores filesystem files that have no corresponding archive member, so it is not a two-way inventory check. A checksum or comparison can establish a narrower integrity fact, but authenticating a handoff needs a trusted digest or signature and a trustworthy source for that reference. Neither gzip's checksum nor tar's header checksums supplies that trust.
Restore permissions as a policy, not a souvenir
An archive can store a numeric user ID, a group ID, their names, mode bits, and modification times. Restoring the same numbers on another machine need not identify the same people. GNU tar can resolve recorded names against the destination's account database; --numeric-owner instead uses numeric IDs. Do not add that option merely because numbers look unambiguous.
By default, ordinary-user extraction applies umask, the mask of permissions to remove, and does not restore ownership. Root's defaults are more preserving. In this controlled restore we explicitly retain the ordinary-user policy and set umask 077, which excludes all group and other access. Parentheses run the settings in a subshell so your interactive mask does not change.
GNU stat reports the resulting mode: -c selects its output format, %a prints octal permission bits, and %n prints the filename. This comparison is about mode bits, not a complete effective-access audit.
( umask 077
mkdir -m 700 private-restore &&
tar -x -f handoff.tar -C private-restore --no-same-owner --no-same-permissions &&
stat -c '%a %n' private-restore/release/app.conf
)600 private-restore/release/app.confThe archive's 640 becomes 600 after the mask removes group read. GNU -p would request the stored permission bits instead; it is not a generic 'make extraction better' option. Ordinary tar metadata is also not a promise to preserve access control lists, extended attributes, or security labels. GNU has separate options such as --acls and --xattrs for the first two; support and restore policy require testing on the destination filesystem.
Inspect links as links
Before extracting an unfamiliar handoff, review member names and types. -v adds a verbose listing, including mode, owner/group, size, time, and link information. GNU --quoting-style=escape makes unusual name bytes visible with escapes. This is a human inspection view, not a lossless pathname manifest to pipe into another command.
The following synthetic bundle adds two kinds of link without following them. ln -s creates a symbolic link containing a target pathname; here current points to app.conf relative to its own directory. Without -s, ln creates a hard link: another name for the same file object. app-copy.conf therefore shares app.conf's data and permissions.
GNU tar normally archives a symbolic link itself, not the file it points to. With the original file first, it can record the second hard-linked name as a link to that member instead of storing another copy of the contents. This creates links.tar and lists it; it does not extract it.
ln -s app.conf release/current &&
ln release/app.conf release/app-copy.conf &&
tar -c -f links.tar -C release app.conf current app-copy.conf &&
tar -t -v -f links.tar --quoting-style=escapeThe three lines identify app.conf as a regular file, current as a symbolic link with '-> app.conf', and app-copy.conf as a hard link with 'link to app.conf'. Owner/group and timestamps vary, so no fixed full transcript is implied. Selecting only a hard-link member for extraction can fail when its target is unavailable. A symbolic link may point outside the restored tree even though the link itself lies inside it; later programs can follow that target. File type matters as much as spelling.
A stored pathname is not permission to write it
An authorized archive review should ask whether member paths or link targets are absolute, contain a parent-directory component (..), or name something other than ordinary files and directories. Tar formats can also describe device nodes and named pipes. Creating or later opening those objects has different consequences from reading a text file; do not restore them merely because a listing succeeded.
This bounded experiment creates a one-member archive whose stored name asks to reach the extraction directory's parent. It uses only our supplied app.conf. GNU --transform changes stored names using a substitution: s,app.conf,../outside.conf, replaces app.conf with ../outside.conf. Commas delimit the expression; single quotes give it intact to tar. This is deliberate fixture generation, not an instruction to use arbitrary transforms on incoming archives.
We list the request, then try ordinary extraction into a new owner-only directory. No -P override is used. In the tested GNU tar 1.35, extraction rejects the parent-directory member. The status is printed immediately, even after failure.
tar -c -f parent-path.tar -C release --transform='s,app.conf,../outside.conf,' app.conf &&
tar -t -f parent-path.tar --quoting-style=escape
mkdir -m 700 rejected &&
tar -x -f parent-path.tar -C rejected --no-same-owner --no-same-permissions
printf 'extract status=%s\n' "$?"../outside.conf
extract status=2Standard error also reports removal of a leading ../ during listing and rejects the '..' member during extraction; exact wording is version-dependent. No outside.conf is created by this test. GNU's Absolute File Names documentation explains leading-slash removal and parent-path restrictions. -P, also named --absolute-names, disables these protections and is not a repair for an unfamiliar archive that refuses extraction.
Listing is preflight, not containment
The previous refusal is a useful tested guardrail, not a proof that arbitrary archives are safe. A list can contain duplicate member names, unexpected object types, misleadingly displayed characters, and links whose consequences appear only when another program follows them. Matching names with a quick text filter does not implement archive-policy validation.
GNU's Security Rules of Thumb recommends extracting untrusted material into an otherwise-empty directory whose ancestry is controlled by trusted users. Its Live Untrusted Data section explains why concurrent changes to destination directories can redirect filesystem operations. A directory chosen with -C cannot prevent another writer from replacing its ancestors.
For a genuinely untrusted archive, use a maintained extraction implementation under a low-privilege identity in an appropriately isolated environment, with bounded storage and no sensitive writable paths. Keep each review separate, inspect the restored objects before opening or executing them, and never run archive-supplied scripts as part of inspection. A private directory reduces accidental collisions and interference; it is not equivalent to an operating-system sandbox.
These are documented capabilities and unsafe-workflow boundaries, not a claim of a newly discovered tar vulnerability or exploitation in the wild. The link bundle and rejected parent path are synthetic tests. No privileged restore or host-file overwrite is needed to understand the risk.
Give a file list an explicit record format
For a larger handoff, a manifest can separate selection from packing. GNU -T reads input filenames from a file instead of taking all of them as command-line operands. Its default line-oriented format has its own interpretation rules, including special treatment of some option-looking lines; it is not automatically safe transport for arbitrary filenames.
Place GNU --null before -T to read NUL-terminated names literally. NUL is the zero byte, which cannot occur inside a Unix pathname. The fixed printf format %s\0 writes each supplied name followed by that byte. The find article explains how -print0 can generate such records from a selection; xargs explains the corresponding input-boundary problem when building arguments.
Here the manifest contains only the two regular files from the original handoff. -C release sets the lookup directory for those names; -T members.nul opens the manifest relative to the original working directory, not release. This creates selected.tar without modifying the sources.
printf '%s\0' app.conf README > members.nul &&
tar -c -f selected.tar -C release --null -T members.nul &&
tar -t -f selected.tarapp.conf
READMEAll consumers must agree about NUL boundaries. GNU --null also disables the filename list's option interpretation, preserving dash-leading names as data. This repairs record transport; it does not freeze a changing source tree or validate what selected files contain.
Choose an interchange format, then test the receiver
Archive format and compression are separate choices. GNU --format=pax selects the POSIX extended tar format, which can represent information beyond the older ustar format's limits. Adding -z would gzip that pax archive; it would not turn it into a different member format. This example creates an uncompressed handoff-pax.tar with the same two top-level names.
POSIX Issue 8 specifies the pax utility and its archive interchange formats. That does not make every GNU tar command-line option POSIX. A program named tar may be GNU tar, bsdtar, or a smaller implementation with different extensions and defaults. Check the receiving program and restore requirements, not just whether its command has the same name.
Pax extensions also do not guarantee that every reader will restore every vendor-specific attribute. Test the real destination with representative long names, link relationships, timestamps, and required access metadata before calling an archive a portable backup.
tar -c --format=pax -f handoff-pax.tar -C release app.conf README &&
tar -t -f handoff-pax.tarapp.conf
READMEThe GNU tar format documentation and POSIX pax specification distinguish format interoperability from command-line portability. Our earlier examples intentionally name the GNU implementation instead of promising identical behavior on every Unix system.
Treat completion as a result worth checking
GNU tar normally returns 0 for success and 2 for a fatal error. Status 1 has operation-specific meaning: comparison found differences, or files changed while being archived during creation, append, or update. A compressor failure also makes tar fail. In a controlled GNU tar 1.35 test, a compressor exited with status 7; tar reported that child status in its diagnostic but returned 2. Retain the diagnostic rather than assuming the child's numeric code is forwarded unchanged. Not every nonzero result means 'bad archive,' and not every warning is fatal.
Warnings are written to standard error and do not, by themselves, change the exit code. A condition that produces a warning can still be associated with an unsuccessful result. Keep diagnostics as well as status; hiding a warning does not repair the condition. A failed creation may leave a partial archive, and a failed extraction may leave already-created members. Neither operation is a transaction with automatic rollback.
A live service can change files between reads even without an error. Plan quiescence or an appropriate snapshot when cross-file consistency matters. Incremental backups add their own history and restore-order contracts; this small handoff deliberately uses complete, separately named archives.
The practical sequence is now explicit: choose the source set and stored names, choose format and compression, retain diagnostics, inspect the archive, compare what needs comparison, and restore under a deliberate path and metadata policy. An archive is a useful transport container—not proof of authenticity, completeness, or safe execution.