Emacs, scripting and anything text oriented.

Disarming the 'tar' bomb in 10 seconds

Kaushal Modi

Use tar -caf <file> <dir> to create an archive, tar -xf <file> to extract one, and more.

I had come across this post by user Garrit on Mastodon, and that inspired this post.

A post on the Unix command tar cannot leave out the obligatory xkcd tar comic 😄, so here it is:

xkcd.com

Mnemonics #

These few mnemonics help me remember the basic and my most frequently used tar options:

  • c to (c)reate
  • a to (a)uto compress the archive based on the file name
  • x to e(x)tract
  • f for the archive (f)ile name we are dealing with (whether creating, listing or extracting an archive)

.. and a few not so frequent options (for me):

  • t to lis(t) contents of an archive
  • v for (v)erbose output

Creating an archive #

tar -caf <file> <dir>

A keen user might have noticed that I am using tar -caf .. instead of tar caf .. i.e. I am using a hyphen before the tar options. Both approaches work and they look similar, but the approach with the hyphen is the newer Short Option style while the other is the Old Option style.

I prefer the short option style because .. well.. the other style is old.. and also because the short option style is stricter e.g. the -f switch has to be followed by the file name.

Whether you are creating a regular .tar archive, or a compressed archive like .tar.gz, always use the auto-compresion switch -a. That relieves you from deciding if you need that switch, or which compression algorithm switch should be used 😄.

The -a switch makes the decision for you based on the file extension. For example, tar -caf foo.tar foo/ will create a regular archive, while tar -caf foo.tar.gz foo/ will create a compressed archive using gzip. You can read more about it in Creating and Reading Compressed Archives.

Extracting an archive #

tar -xf <file>

At times, it might be useful to add the verbosity switch -v to this command and do tar -xvf <file>.

Just to reiterate, the -f switch must be followed by the archive file name.

Listing contents of an archive #

tar -tf <file>

Once you are done creating an archive, you might feel the need to check if the archive contains everything you expect. Or you might want to check what’s inside the archive before you extract it.

This command is often paired with grep or rg (ripgrep) like so: tar -tf foo.tar.xz | rg 'some_file_name_in_archive'.

Summary #

If you simply glossed over the whole article, or didn’t read through the all linked manual pages  I know you didn’t 😉 , just remember this —

tar -caf to c​reate and tar -xf to e​x​tract