Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using zip and unzip - File Compression

Introduction

File compression is a method to reduce the size of files, making them easier to store and transfer. This tutorial will cover the basics of using the zip and unzip commands in the command line for compressing and decompressing files.

Installing zip and unzip

Most Unix-based systems come with zip and unzip pre-installed. To check if they are installed, you can run the following commands:

which zip

which unzip

If they are not installed, you can install them using your system's package manager. For example, on Debian-based systems, you can use:

sudo apt-get install zip unzip

Creating a Zip Archive

To create a zip archive, use the zip command followed by the name of the archive and the files you want to include. For example:

zip archive.zip file1.txt file2.txt

This command will create a file named archive.zip containing file1.txt and file2.txt.

To include directories, use the -r (recursive) option:

zip -r archive.zip directory_name

Viewing the Contents of a Zip Archive

To view the contents of a zip archive without extracting it, use the unzip command with the -l (list) option:

unzip -l archive.zip

Archive: archive.zip

Length Method Size Ratio Date Time CRC-32 Name

-------- ------ ------- ----- ---- ---- -------- ----

123 Defl:N 45 63% 01-01-22 10:00 a1b2c3d4 file1.txt

456 Defl:N 123 73% 01-01-22 10:01 e5f6g7h8 file2.txt

-------- ------- --- -------

579 168 71% 2 files

Extracting a Zip Archive

To extract the contents of a zip archive, use the unzip command followed by the name of the archive:

unzip archive.zip

This command will extract all files in the archive to the current directory. To extract to a specific directory, use the -d option:

unzip archive.zip -d /path/to/destination

Updating a Zip Archive

To add new files to an existing zip archive, use the zip command with the -u (update) option:

zip -u archive.zip newfile.txt

Deleting Files from a Zip Archive

To delete files from a zip archive, use the zip command with the -d (delete) option:

zip -d archive.zip file1.txt

Password Protecting a Zip Archive

To create a password-protected zip archive, use the -e (encrypt) option:

zip -e archive.zip file1.txt file2.txt

You will be prompted to enter and verify the password.

Summary

In this tutorial, we covered the basics of using the zip and unzip commands for file compression and decompression. We discussed how to create, view, extract, update, delete, and password-protect zip archives. With these commands, you can efficiently manage your compressed files from the command line.