How Do I Zip All Files In A Directory In Linux?

Zip is a lossless data compression utility supported by all Linux distributions.

Zip archives refer to container archives that contain one or more compressed files and directories. Zip files are cross-platform, allowing you to create zip archives in Windows, Linux, and macOS using various utilities. In addition, zip archive files take less space, making them easier to transfer and store.

In Linux, we use the zip archive utility to create zip archives. Throughout this tutorial, we will focus on how to go about creating zip archives in Linux using the zip utility.

Install Zip

Depending on your Linux distribution, you will need to install the zip utility. Since all Linux distributions support it, you can use the package manager to install it.

For Debian/Ubuntu

On Debian, use the command:

sudo apt-get update
sudo apt-get install zip -y

For REHL/CentOS

On CentOS and REHL family, use the command:

sudo yum update
sudo yum install zip

The Zip Command

The zip command is simple to use. The general syntax for the command is:

zip [OPTION] zip_name file(s)

To create a zip archive of more than one file, pass them in a list (separated by space) after the zip filename. It is also good to ensure you have to write permissions in the directory you are creating the zip file.

How to Zip Files In Linux

We can zip files in a directory as:

zip myarchive.zip file1, file2, file3, file3

The command above displays the name of the file added to the archive and the compression method.

Zip utility automatically adds a .zip extension to the archive filename—if not explicitly specified.

How to Compress Zip Directories In Linux

You can compress directories and the corresponding sub-directories by using the -r flag. The -r flag will tell zip to traverse the entire directory recursively.

For example, consider the /var/log directory. To create an archive of all the files and directories, we use the command:

sudo zip -r logs.zip /var/log

To suppress the output from the compression process, use the -q for quiet mode. The command creates a zip archive of the specified files with no output.

sudo zip -q zipname.zip files

How to Zip all Files in a Directory In Linux

What if you want to zip all files in a directory? In that case, we use wildcard expressions to do this.

sudo zip -q logs.zip /var/log/*

The above command adds all the files and directories in the specified path and adds them to the zip archive.

How to Zip All Files, Including Hidden Files

To add even hidden files to a zip archive, use the wildcard (.* *). The command for that is:

sudo zip -q logs.backup.zip /var/log/.* *

Conclusion

As shown in this tutorial, Linux allows you to create zip archives. You can use any archive utility such as WinRar, 7zip, unzip; to unarchive the files.

Thank you for reading!