Archives with tar and gzip

Intermediate · 8 min

Bundle a directory with tar, compress with gzip, list before extracting, and avoid the traps: leading slashes, -C, and macOS zcat. Tested with bsdtar.

Before thisCreating, copying, moving and removingPipes and pipelinesRedirection

Bogdan Stashchuk · 8 min

Archives with tar and gzip

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Bogdan StashchukReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • tar bundles many files into one stream (the archive) and gzip compresses one stream. A .tar.gz is both, which tar -z does in one step.
  • Remember the flags as verbs: c create, x extract, t list, z gzip, f file name, v verbose. Always list with tar -tzf before you extract an archive you did not make.
  • Use -C dir to choose where to extract or what to archive from, and --strip-components=1 to drop the top directory. Nothing is extracted into a new folder automatically.
  • gzip file replaces the file with file.gz. Use gzip -k to keep the original and gzip -dc to read the contents, since the zcat command behaves differently on macOS.
  • tar strips a leading / from stored paths so extraction cannot overwrite system files. Archive relative paths with -C instead.

Two problems, two tools

You want to send a directory to someone, or keep a backup of it. Two things stand in the way.

First, a directory is many files with permissions and timestamps, and most ways of moving data want a single stream. Second, text and logs are repetitive and compress well. The Unix answer is two small tools that each do one job. tar, short for tape archive, glues files into one stream and records their names and permissions. gzip compresses one stream and knows nothing about files. Combined, you get the .tar.gz (or .tgz) that you see everywhere.

I ran everything below on macOS, whose tar is bsdtar 3.5.3 (libarchive), against the fixture project with logs/ and data/. The GNU tar on Linux takes the same core flags, but I did not run it, so where I mention it that is from its documentation.

Create, list, extract

$ tar -czf proj.tar.gz proj
$ ls -l proj.tar.gz | awk '{print $5, $NF}'
3306 proj.tar.gz
$ tar -tzf proj.tar.gz | head -5
proj/
proj/logs/
proj/data/
proj/data/people.csv
proj/data/users.json

Read the flags as verbs. c creates, x extracts, t lists, z runs it through gzip, and f says the next word is the archive’s file name. So -czf is “create, gzipped, to this file”, and the order is not arbitrary: f must come right before the file name. I ran tar -czvf with nothing after it and got tar: Option -f requires an argument. v makes it print each file as it goes:

$ tar -czvf v.tar.gz proj/data
a proj/data
a proj/data/people.csv
a proj/data/users.json

Extraction goes into the current directory, so I extracted into a fresh one with -C:

$ mkdir out && tar -xzf proj.tar.gz -C out && ls out/proj
data
logs

-C works for creating as well. Archiving from inside a directory keeps the top folder out of the stored paths:

$ tar -czf flat.tar.gz -C proj data logs
$ tar -tzf flat.tar.gz | head -3
data/
data/people.csv
data/users.json

If an archive already has a top directory you do not want, --strip-components=1 removes the first path level when extracting. Extracting proj.tar.gz that way with -C strip left data and logs directly in strip. Both bsdtar and GNU tar support this flag.

List before you extract

An archive does not have to unpack into one directory, and extraction writes where you tell it, overwriting without asking. Run tar -tzf first and look at the top level. A tarball that scatters files across your current directory is called a tarbomb. Listing costs nothing.

Pull out a single file to standard output, with no extraction to disk, using -O:

$ tar -xzf proj.tar.gz -O proj/data/people.csv | head -2
name,team,city,score
ada,infra,london,91

Leading slashes

If you archive an absolute path, tar takes the leading / off, and says so:

$ tar -cf abs.tar /tmp/lessonabs
tar: Removing leading '/' from member names
$ tar -tf abs.tar
tmp/lessonabs/
tmp/lessonabs/f.txt

That protects you on extraction: files land under the directory you chose rather than over /tmp itself. I confirmed with -C absout, which produced absout/tmp/lessonabs/f.txt. The better habit is to cd or use -C and archive relative names.

gzip by itself

gzip works on one file and, unlike cp, it replaces your original:

$ gzip a.log
$ ls a.log*
a.log.gz
$ gzip -l a.log.gz
  compressed uncompressed  ratio uncompressed_name
        2328        14362  83.7% a.log

Use gzip -k to keep the original, and gzip -d (or gunzip) to reverse it. To read without unpacking, gzip -dc file.gz writes to standard output. On macOS the zcat command is not what you expect:

$ zcat p.csv.gz
zcat: can't stat: p.csv.gz (p.csv.gz.Z): No such file or directory
$ gzip -dc p.csv.gz | head -1
name,team,city,score

macOS’s zcat belongs to the older compress tool and looks for .Z files. gzcat (and gzip -dc) read .gz. On Linux zcat reads gzip files, which is why this surprises people moving between machines.

The level trades time for size. On my 14 KB log, gzip -1 gave 2767 bytes and gzip -9 gave 2290. For log files, the default is almost always fine.

Archives in pipelines

tar writes to standard output with -f -, so it composes with the pipes you know. Copying a tree through a pipe, preserving permissions, is a classic:

$ tar -cf - proj | tar -xf - -C out && echo copied
copied

For other formats, tar -caf name.tar.xz dir picks the compressor from the file extension. I confirmed it produced XZ data. A damaged or fake archive fails clearly:

$ tar -tzf bad.tar.gz
tar: Error opening archive: Unrecognized archive format

macOS can also add ._ metadata entries for files with extended attributes. I did not see any in my test, so I will not claim more than that this exists. Setting COPYFILE_DISABLE=1 stops it on a Mac, and I did not run the case that needs it.

About the video

“Linux Tutorial: 41 Creating and extracting compressed archive using tar and gzip” is a 7-minute 45-second video from Bogdan Stashchuk, part of a beginner Linux course, published November 2020. The description is only links and has no chapters, and I could not read a transcript. I am going by the title. It is an English-language channel, and it is Linux-based, so flags like zcat may behave differently on a Mac.

Where this fits

You can bundle and compress. Archives are easy to grow without noticing, so the next lesson is how to see where the space went: disk usage with df and du.

Check yourself

  1. 01You downloaded project.tar.gz. What do you run before extracting it, and why?

    tar -tzf project.tar.gz. It lists the contents so you can see if it unpacks into one directory or spills dozens of files into the current one.

  2. 02How do you extract an archive into /tmp/out rather than the current directory?

    tar -xzf archive.tar.gz -C /tmp/out. The directory must exist already.

  3. 03What is the difference between tar -czf out.tar.gz proj and tar -czf out.tar.gz -C proj .?

    The first stores every path under proj/. The second changes into proj first and stores paths relative to it, so extracting gives the contents without an extra proj/ level.

  4. 04On a Mac, zcat file.gz says it cannot stat file.gz.Z. What do you use instead?

    gzip -dc file.gz, which works on macOS and Linux. macOS zcat is the older compress tool, and gzcat is its gzip equivalent.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark