Skip to content
AgileLogics
4 min read

Archives and Compression

Prerequisites: Working with files and directories

tar bundles files and folders into one archive; gzip compresses it. Together they're the standard way to package and back up files on Linux.

Creating and inspecting archives

mkdir -p site/css site/js
echo "body {}" > site/css/style.css
echo "console.log(1)" > site/js/app.js
echo "<h1>Hi</h1>" > site/index.html

tar -czf site.tar.gz site
tar -tzf site.tar.gz | sort
site/
site/css/
site/css/style.css
site/index.html
site/js/
site/js/app.js

The option letters:

  • -c create, -x extract, -t list contents
  • -z gzip compression (-j bzip2, -J xz)
  • -f the archive file name (must come last before the name)
  • -v verbose

Mnemonics help: tar -czf = "create zipped file"; tar -xzf = "extract zipped file".

Extracting

mkdir -p site && echo "hi" > site/index.html
tar -czf site.tar.gz site
rm -r site

mkdir restore
tar -xzf site.tar.gz -C restore
find restore -type f
restore/site/index.html

-C folder extracts into a different folder.

zip, gzip, and friends

  • gzip file / gunzip file.gz — compress or decompress a single file.
  • zip -r site.zip site / unzip site.zip — the ZIP format, handy when sharing with Windows users.
  • zcat file.gz, zgrep pattern file.gz — read compressed files without extracting them — useful for rotated log files.

Common mistakes

  • Extracting an archive from the internet without looking inside first. Run tar -tzf to check it won't scatter files everywhere.
  • Archiving with absolute paths (tar -czf b.tar.gz /home/ada/site), which recreates the full path on extraction. cd to the parent folder first, or use -C.