In the Linux world, compressing and extracting files is a daily occurrence. Whether you are backing up a database, downloading open-source software, or sending a batch of log files to a developer, you need a way to bundle multiple files into a single, smaller archive. While the tar command is traditional in Unix environments, the standard zip format remains the most universally compatible way to share files across Linux, Windows, and macOS.
Ubuntu allows you to manage these archives effortlessly from the command line, bypassing the need for clunky graphical archive managers.
Checking for Required Packages
Unlike tar, the zip and unzip utilities are not always pre-installed on every minimalist Ubuntu server (though they are usually present on the desktop version). It is good practice to ensure you have them installed before you begin.
Open your terminal and run:
sudo apt update && sudo apt install zip unzip
How to Zip Files and Directories
1. Zipping a Single File
The basic syntax for the zip command requires you to name the archive you want to create first, followed by the file(s) you want to put inside it.
zip archive_name.zip file1.txt
This command creates a new file called archive_name.zip containing file1.txt.
2. Zipping Multiple Files
To compress several files into one archive, simply list them separated by a space.
zip my_documents.zip report.pdf budget.xls presentation.ppt
3. Zipping an Entire Directory (Folder)
If you want to compress a folder and all the files and subfolders inside it, you must use the recursive flag (-r). If you forget this flag, the command will only zip the empty folder structure.
zip -r website_backup.zip /var/www/html/
4. Creating a Password-Protected Zip
If you are sending sensitive information, you can encrypt the zip file by adding the -e (encrypt) flag. The terminal will securely prompt you to type and verify a password before generating the file.
zip -e secure_data.zip passwords.txt
How to Unzip Files
1. Basic Extraction
To extract the contents of a zip file into your current working directory, use the unzip command followed by the filename.
unzip downloaded_files.zip
2. Extracting to a Specific Directory
If you do not want the files to clutter your current location, you can direct the output to a specific folder using the -d (destination) flag. If the folder does not exist, the command will create it for you.
unzip downloaded_files.zip -d /home/user/new_folder/
3. Viewing the Contents Without Extracting
Sometimes you download a mysterious zip file and want to see what is inside before cluttering your hard drive. Use the -l (list) flag to view the contents without unzipping them.
unzip -l mysterious_file.zip
Conclusion
While graphical tools are fine for the occasional download, mastering the zip and unzip commands allows you to handle backups, server migrations, and automated scripts with speed and precision directly from the Ubuntu terminal.