zip, gzip, bzip2 Linux Commands with Exercises

2022-03-12

zip, gzip, bzip2 are Linux commands commonly used when compressing, decompressing, or archiving files.

  • zip: compress files or directories and archive them in .zip format. And extract .zip file.
  • gzip: compress a file as .gz format. And decompress .gz file.
  • bzip2: compress a file as .bz2 format. And decompress .bz2 file.

Each command has a corresponding format so is not compatible with other formats.
For example, zip command cannot extract .gz files. gzip command cannot decompress .bz2 files. bzip2 command cannot decompress .gz files, and so on.

In this article, for beginners (most likely contains me), I listed easy exercises for each command. It may be too easy, but I think it will be useful for true beginners.

For the tar command, please check the post.



zip Exercise

In advance, create two files which contain some text.

1
2
echo "Hello" >> hello.txt
echo "World" >> world.txt

Zip the two files.

1
2
3
4
5
6
zip helloworld hello.txt world.txt
# adding: hello.txt (stored 0%)
# adding: world.txt (stored 0%)

ls
# helloworld.zip hello.txt world.txt

helloworld is the name of the archive to be created. As such the helloworld.zip will be created.

Now, delete the original two text files for the next section(unzip).

1
2
3
4
rm *.txt

ls
# helloworld.zip

Unzip the .zip file using unzip command.

1
2
3
4
5
6
7
unzip helloworld
# Archive: helloworld.zip
# extracting: hello.txt
# extracting: world.txt

ls
# helloworld.txt hello.txt world.txt

Extracting the helloworld.zip, the two original files will appear.



gzip Exercise

First of all, create a text file which has some text.

1
echo "Hello" >> hello.txt

Compress the file using gzip.

1
gzip hello.txt

The hello.txt.gz will be created. To check the file type, run the following command.

1
2
file hello.txt.gz
# hello.txt.gz: gzip compressed data, was "hello.txt", last modified: Sat Mar 12 05:39:29 2022, from Unix, truncated

Next, decompress the hello.txt.gz using gzip or gunzip.

1
2
3
4
5
# For gzip
gzip -d hello.txt.gz

# For gunzip
gunzip hello.txt.gz

After that, the original text file named hello.txt will appear.

1
2
file hello.txt
# hello.txt: ASCII text



bzip2 Exercise

As with previous exercises, create a text file.

1
echo "Hello" >> hello.txt

Compress the file using bzip2.

1
bzip2 hello.txt

The hello.txt.bz2 will be created.

1
2
file hello.txt.bz2
# hello.txt.bz2: bzip2 compressed data, block size = 900k

Decompress the hello.txt.bz2 using bzip2 or bunzip2.

1
2
3
4
5
# For bzip2
bzip2 -d hello.txt.bz2

# For bunzip2
bunzip2 hello.txt.bz2

The original hello.txt file will return in front of us.

1
2
file hello.txt
# hello.txt: ASCII text