A Guide to Compressing and Decompressing Files in Linux
Compressing files saves disk space and makes data transfers faster. This article will guide you through the most common command-line tools for compressing and decompressing files and directories in the Linux operating system.
Understanding the Core Concepts: TAR vs. GZIP/BZIP2/XZ
To properly use the commands, you need to understand two distinct concepts:
Therefore, a .tar.gz
file is essentially a group of files bundled by tar
and then compressed by gzip
to save space.
1. The .tar.gz (or .tgz) Format
This is the most popular compression format on Linux, using the gzip
algorithm.
Compressing Files and Directories
Use the -z
flag in the tar
command to compress directly.
tar -czvf archive.tar.gz /home/user/public_html
Decompressing Files
Use the -x
(extract) flag to decompress.
tar -xzvf archive.tar.gz
# Extract to a specific directory
tar -xzvf archive.tar.gz -C /home/user/backups
Viewing the Contents of a Compressed File
Use the -t
(list) flag to view the contents without decompressing.
2. The .tar.bz2 Format
This format uses the bzip2
algorithm, which often provides slightly better compression than .gz
but takes more time.
Compressing Files and Directories
Use the -j
flag.
tar -cjvf archive.tar.bz2 /home/user/public_html
Decompressing Files
Use the -j
flag.
3. The .zip Format
This format is very common and highly compatible with Windows. The zip
and unzip
commands handle both archiving and compression in one step.
Compressing Files and Directories
Use the zip
command with the -r
(recursive) flag to include subdirectories.
zip -r archive.zip /home/user/public_html
Decompressing Files
# Extract to a specific directory
unzip archive.zip -d /home/user/backups
Viewing the Contents of a Compressed File
Explanation of TAR Command Flags
-c
(create): Create a new archive.-x
(extract): Extract files from an archive.-t
(list): List the contents of an archive.-v
(verbose): Show the progress in detail.-f
(file): Specify the archive file name to work with.-z
: Use the gzip compression algorithm.-j
: Use the bzip2 compression algorithm.-C
: Specify a target directory to extract files into.