← Linux and the Command Line Lesson 32 of 51 · 10 XP

tar — Linux archives

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

tar (tape archive) gathers many files into one. Compression is done by a separate program, gzip or xz, but tar can call it by itself.

The options read like a phrase:

c create
x extract
t list the contents
z compress / decompress with gzip (.tar.gz, .tgz)
J xz (.tar.xz) — stronger, but slower
v verbose — print the file names
f file — the archive name comes next (it goes last!)
tar czf backup.tar.gz project/        # pack a folder
tar tzf backup.tar.gz                 # see what's inside
tar xzf backup.tar.gz                 # unpack here
tar xzf backup.tar.gz -C /tmp/restore # unpack into another folder

f must come last, because the archive name follows it straight away: tar czf archive.tar.gz what_to_pack.

An administrators' joke: "you have 10 seconds to unpack a tar correctly without Googling, or the bomb goes off". With the phrases "create zipped file" and "extract zipped file" you'll defuse it.

What z does under the hood. By itself, tar only glues files together into one stream, and gzip does the compression. The z option simply plugs it in. You can do the same with a pipe if the file name is - ("standard input/output"):

tar cf - notes.txt todo.txt | gzip > backup.tar.gz     # = tar czf backup.tar.gz notes.txt todo.txt
gzip -dc backup.tar.gz | tar tf -                      # = tar tzf backup.tar.gz
gzip -dc backup.tar.gz | tar xf - -C restore           # = tar xzf backup.tar.gz -C restore

In our mini Linux, tar is built without the z option, as on some minimal servers and routers, so it's the pipe that comes in handy. This version works everywhere.

Task. Pack the files notes.txt and todo.txt into a compressed archive backup.tar.gz with a tar | gzip pipe. Print the sorted list of the archive's files. Then unpack it into a new folder restore and print restore/todo.txt.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.