Archiving files with tar
- Version
- unversioned
- Review
- Draft
Summary#
tar packs files into one archive and extracts them again. Choose an operation with -c to create, -t to list or -x to extract; -z selects gzip compression.
Syntax#
tar -czf archive.tar.gz -C parent directory
tar -tzf archive.tar.gz
tar -xzf archive.tar.gz -C destination
-C changes directory before the following files are handled. The destination directory must already exist.
Example#
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
mkdir -p project/src restore
echo 'print("hi")' > project/src/main.py
echo 'Demo project' > project/README
tar --sort=name -czf backup.tar.gz project
tar -tzf backup.tar.gz
tar -xzf backup.tar.gz -C restore --strip-components=1
echo '-- restored without the top directory'
LC_ALL=C find restore -type f | LC_ALL=C sort
)
Expected output#
project/
project/README
project/src/
project/src/main.py
-- restored without the top directory
restore/README
restore/src/main.py
Common mistakes#
With dashed short options, -f takes the rest of its option group as the archive name. tar -cfz backup.tar.gz project can write an archive named z. Put f last, as in -czf. Creation can overwrite an existing archive. Extraction can replace existing files, so list members with -t and use a new empty directory for archives you do not trust.
Version applicability#
The example needs GNU tar 1.28 or later for --sort=name, which gives a stable member order. The bsdtar command that macOS provides as tar does not support this option.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0