How to zip files and folders in Linux?
Zipping files and folders in Linux is a common operation for file compression and archiving. The most commonly used tools for this task are zip
and gzip
, though zip
is particularly versatile for creating .zip
archives that are commonly used across different operating systems. Here’s how to use the zip
command in Linux to compress files and folders:
Installing the 'zip' Utility
Before you can use the zip
command, make sure it's installed on your system. You can install it using your distribution’s package manager.
For Ubuntu/Debian-based systems:
sudo apt update sudo apt install zip
For CentOS/RHEL-based systems:
sudo yum install zip
For Fedora:
sudo dnf install zip
Basic Syntax of the 'zip' Command
The basic syntax of the zip
command is:
zip [options] [output_file.zip] [list_of_files_or_directories]
Examples
Here are several examples of how to use the zip
command:
-
Zip a Single File
zip output.zip file1.txt
-
Zip Multiple Files
zip output.zip file1.txt file2.txt file3.txt
-
Zip a Folder To zip a folder and its contents recursively, use the
-r
(recursive) option:zip -r output.zip foldername/
-
Zip Multiple Folders
zip -r output.zip folder1 folder2
-
Zip Files Using a Pattern You can also use wildcards to specify a pattern for files to zip:
zip output.zip *.txt
This command zips all
.txt
files in the current directory. -
Exclude Specific Files or Directories If you want to exclude certain files or directories when zipping, use the
-x
option:zip -r output.zip foldername/ -x *.mp4
This command will zip everything inside
foldername/
except.mp4
files. -
Set Compression Level The
-0
to-9
options set the compression level, where-0
means no compression (store only) and-9
means maximum compression:zip -r -9 output.zip foldername/
-
Split the Zip into Smaller Parts If you need to create a multi-part zip file due to size constraints (like email attachments), use the
--split-size
option:zip -r -s 64m output.zip foldername/
This will create parts of the archive, each with a maximum size of 64MB.
-
Password Protect a Zip File Use the
-e
option to encrypt the zip file and set a password:zip -e protected_output.zip file1.txt
Unzipping Files
To unzip files, use the unzip
command:
unzip output.zip
Notes
- The
zip
utility is versatile and supports a wide range of options that can be viewed by runningman zip
orzip --help
. - For strictly Unix environments, you might also consider using
tar
combined with compression tools likegzip
orbzip2
for more Unix-centric features.
Using the zip
command in Linux allows for easy compression and archiving of files and folders, making it simpler to manage file sizes and transport files across different systems securely and efficiently.
GET YOUR FREE
Coding Questions Catalog