3  File Compression

3.1 Introduction

In Linux, gzip and bzip2 are essential for file compression, producing .gz and .bz2 files respectively. Their counterparts, gunzip and bunzip2, are used for decompression.

For directories, the tar command bundles files into an archive before compression with gzip or bzip2. This guide outlines these processes, including single-command archive and compression.



3.2 Creating an Archive

To bundle a directory into a single archive file:

tar -cvf myarchive.tar my_folder_to_archive/

Options explained:

  • -c: Create archive
  • -v: Verbose output
  • -f: Specify archive file name

3.2.1 Viewing Archive

Without extracting, list archive contents with:

tar -tf myarchive.tar

3.2.2 Adding Files to an Archive

To append files to an existing archive:

tar -rvf myarchive.tar supplementary_file.txt

3.2.3 Extracting Archives

Unpack an archive using:

tar -xvf myarchive.tar

3.3 Compression Techniques

3.3.1 Using gzip and bzip2

To compress an archive:

# Produces myarchive.tar.gz
gzip myarchive.tar 

# Produces myarchive.tar.bz2
bzip2 myarchive.tar  

3.3.2 Decompression Commands

For decompression:

gunzip myarchive.tar.gz
bunzip2 myarchive.tar.bz2

3.4 Efficient Archive and Compression

Archive and compress in one step:

# With gzip
tar -zcvf myarchive.tar.gz my_folder_to_archive/  

# With bzip2
tar -jcvf myarchive.tar.bz2 my_folder_to_archive/  
Note

Options -z for gzip and -j for bzip2.

For decompression:

# With gzip
tar -zxvf myarchive.tar.gz  

# With bzip2
tar -jxvf myarchive.tar.bz2  

3.5 Reading Compressed Files

Tools for viewing compressed file contents without decompression:

  • zcat: Displays content
  • zmore & zless: Page-by-page content browsing

Example with zcat:

zcat myfile.txt.gz

3.6 Handling .zip and .rar Files

3.6.1 Zip Files

Check zipped content with:

unzip -l myfile.zip

To extract:

unzip myfile.zip

To create a zip archive:

zip -r myfolder.zip myfolder/

3.6.2 Rar Files

View .rar contents:

unrar l myfile.rar

Extract .rar files:

unrar e myfile.rar
Note

Note: Creating .rar files requires purchasing software, making .zip a more accessible option for many users.