To zip a file in Linux or macOS, we can use the
zip [options] zipfile_name filename_separated_by_space
zipcommand is not present in your system, install it with:
sudo apt install zip
Suppose we are in the folder project and the following is the structure of the project folder.
project │ README.md │ file1.txt │ │ └───folder_1 │ │ file011.txt │ │ file012.txt │ │ │ └───subfolder_1 │ │ file1_1_1.txt │ │ file1_1_2.txt │ │ ... │ └───folder_2 │ file2_1.txt │ file2_2.txt
To zip files, we need the zipped filename and the files to be included in the zip file.
zip test.zip README.md
zip command prints the names of the files added to the zip file and the
adding: README.md (stored 77%)
To hide the above message, we can use the
zip -q test.zip README.md
The above code will not print the files added or the compression method in the terminal.
To zip all the files in a folder, we can use
* instead of specifying all the filenames.
zip allfiles.zip *
The above command will zip all the files and folders (files inside the folder are not included) in the current directory.
To zip a folder, we can add the following folder name.
zip folders.zip folder_1
The above code will only zip the files in the folder_1. The files in the subfolders of folder_1 will not be compressed.
To add all files in the folder and subfolder, we can use the
-r command, which will compress all the files in the folder.
zip -r folders.zip folder_1
The above code will zip all the files recursively in folder_1. The folder structure is maintained in the zip file.
We can also combine multiple folders and files by recursively zipping files.
zip -r multiplefolder.zip folder_1 folder_2 README.md
We can use
Let’s add file1.txt and update README.md in text.zip.
zip -u text.zip file1.txt README.md
The zip file will only be updated if the existing file is modified or if the file is not present in the zip.
To delete a file from the compressed file, we can use
zip -d multiplefolder.zip README.md
We can use the
-m command to delete the original files after the zip file is created.
zip -m test.zip README.md
The above command will delete README.md.
We can use
-e to create a password-protected zip file.
zip -e secret.zip README.md
The above command will ask for a password.
Enter password: Verify password:
The compression level defines how optimally the files can be compressed. The compression levels range from 0-9 but, by default, the compression level is 6. To change the compression level, we can use
zip -9 optimized.zip *
The above code will zip files with the optimal compression. If we give -9, the CPU takes more time to create the zip, but the zip file size will be less. If we specify -0, the zip files are created without compression.
View all Courses