Linux Basics: Creating and Extracting tar Archives
A .tar.gz file bundles files and directories into one gzip-compressed archive. Debian and Ubuntu provide tar for creating, listing, and extracting these archives.
Create an archive
Run mktemp -d, then use cd to enter the new temporary directory. Create some practice content:
mkdir notes
printf 'Remember the backup\n' > notes/todo.txt
tar -czf notes.tar.gz notesThe options have separate jobs: -c creates an archive, -z uses gzip compression, and -f names the archive file. The argument immediately after -f is notes.tar.gz; notes is the directory to include.
The original directory stays in place. Keep the archive outside the directory you are archiving, as this example does.
Check what is inside
tar -tzf notes.tar.gz-t lists the archive’s entries without extracting them. Check these paths before unpacking an archive, especially when you received it from someone else. Listing an archive does not prove it is safe; only extract archives you trust.
Extract into a separate directory
mkdir restored
tar -xzf notes.tar.gz -C restored
cat restored/notes/todo.txtRemember the backup-x extracts files. -C restored tells tar to change into the existing restored directory first. The archived notes directory is recreated beneath it.
Use a new, empty destination to avoid overwriting existing files. You can compare the restored content with the original before deciding whether the archive is useful as a backup. A copy on the same disk does not protect against disk failure.
Reference
Acknowledgements
This post was created with assistance from AI.
Linux Basics — lesson 14 of 25. Series index
Previous: Creating Symbolic Links · Next: Checking File Integrity with SHA-256