Bash tar Archives
Round-trip a known text file through a new archive.
How it works
tar stores multiple filesystem entries in an archive; compression is a separate layer selected by appropriate options. An archive can contain paths and links, so extracting an unknown archive into a sensitive directory is unsafe. Inspect entries and use a fresh destination. This exercise creates its own one-file archive and verifies extracted bytes rather than assuming a successful listing proves content integrity.
Run the code
Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.
This complete example was executed in the stated local review environment.
The complete source creates a fresh private temporary workspace and checks its physical path before cleanup. All file fixtures belong to that workspace; do not remove the guards or point it at existing documents.
Example
#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
# Own a new directory; verify physical paths before cleanup.
parent=$(cd -- "${TMPDIR:-/tmp}" && pwd -P) || exit 1
work=$(mktemp -d "$parent/bhylu-bash.XXXXXX") || exit 1
work=$(cd -- "$work" && pwd -P) || exit 1
case "$work" in "$parent"/bhylu-bash.??????) ;; *) exit 1 ;; esac
cleanup() {
cd -- "$parent" || return 1
[[ -d $work && ! -L $work ]] || return 1
[[ $(cd -- "$work" && pwd -P) == "$work" ]] || return 1
case "$work" in "$parent"/bhylu-bash.??????) rm -r -- "$work" ;; *) return 1 ;; esac
}
trap cleanup EXIT
cd -- "$work" || exit 1
mkdir -- source restored
printf "map revision 1\n" > source/map.txt
tar -cf maps.tar -C source map.txt || exit 1
tar -tf maps.tar | grep -Fx -- map.txt >/dev/null || exit 1
tar -xf maps.tar -C restored || exit 1
cmp -- source/map.txt restored/map.txt || exit 1
printf "Owned tar archive restored exactly\n"
Focus on the lesson commands
This excerpt omits temporary-workspace setup and cleanup. Use the complete source above to run the example.
mkdir -- source restored
printf "map revision 1\n" > source/map.txt
tar -cf maps.tar -C source map.txt || exit 1
tar -tf maps.tar | grep -Fx -- map.txt >/dev/null || exit 1
tar -xf maps.tar -C restored || exit 1
cmp -- source/map.txt restored/map.txt || exit 1
printf "Owned tar archive restored exactly\n"
Expected result
Owned tar archive restored exactly
The archive contains one explicitly named relative entry. Extraction goes into the newly created restored directory, not the application or a home folder. Real external archives require review for unexpected paths, links and resource use; this trusted round trip does not implement a general secure archive extractor.
Primary technical reference: Bash documentation.