Linux: Working With Archives

📄 Wiki page | 🕑 Last updated: Apr 5, 2022

Working with archives in the shell is simple, you just need to understand two concepts: compression and archiving (and how they fit together).

First, let's take a look at the compression part. gzip, bzip2 and xz are the most common compression formats in the Linux world.

gzip, bzip2 & xz

Compressing a file:

gzip myfile
bzip2 myfile
xz myfile

Uncompressing a file:

gunzip myfile.gz
bunzip2 myfile.bz2
unxz myfile.xz

If (for some weird reason) you don't already have any of those tools installed, you can install them with something like apt install gzip bzip2 xz-utils tar.

This works great for a single file, but it's not easy to create archives of multiple files/directories this way, so we need tar.

tar

Making a tar archive of multiple files/directories is easy:

tar cvf archive.tar path1 path2

Now that we have a single file, we can easily compress it:

gzip archive.tar
bzip2 archive.tar
xz archive.tar

We could pipe the result of tar command to gzip/bzip2/xz, but that's still a bit cumbersome, so we can tell tar command directly to combine those two steps for us:

tar czvf archive.tar.gz path1 path2
tar cjvf archive.tar.bz2 path1 path2
tar cJvf archive.tar.xz path1 path2

(just remember that z switch stands for gzip, j for bzip2, and J for xz compression)

Extracting archives:

tar xvf archive.tar
tar xzvf archive.tar.gz
tar xjvf archive.tar.bz2
tar xJvf archive.tar.xz

In terms of efficiency, xz generally has the highest compression rate, and it's faster than bzip2 at decompressing (at the expense of the compression time). gzip has the lowest compression rate, but it's fast.

Other formats

These formats are more common on other platforms than Linux, but working them from CLI is generally as easy as with tar archives.

zip

Creating archives:

zip archive.zip path1 path2

Extracting archives:

unzip archive.zip

Note:

rar

Creating archives:

rar a archive.rar path1 path2

Extracting archives:

unrar e archive.rar

To extract the archive to a specific directory, just add it at the end:

unrar e archive.rar /destination_dir

Note:

7z

Creating archives:

7z a archive.7z path1 path2

Extracting archives:

7z e archive.7z

Note:


Ask me anything / Suggestions

If you have any suggestions or questions (related to this or any other topic), feel free to contact me. ℹī¸


If you find this site useful in any way, please consider supporting it.