Linux – How to zip files with a size limit

bashgziplinux

I have a script that zip files from a folder. I want to make sure that the zipped file is not more than 10 MB. If the size is more than 10MB, it should create another ZIP file.

Is there any command (or other method )that can be used for this?

Best Answer

You can use the "split archive" functionality of "zip" itself using the "--split-size" option.

From "zip" manpage ("man zip"):

(...)

One use of split archives is storing a large archive on multiple remov‐
able media. For a split archive with 20 split files the files are typ‐
ically named (replace ARCHIVE with the name of your archive) AR‐
CHIVE.z01, ARCHIVE.z02, ..., ARCHIVE.z19, ARCHIVE.zip. Note that the
last file is the .zip file.

(...)

-s splitsize
--split-size splitsize

Split size is a number optionally followed by a multiplier.
Currently the number must be an integer. The multiplier can
currently be one of k (kilobytes), m (megabytes), g (gigabytes),
or t (terabytes). As 64k is the minimum split size, numbers
without multipliers default to megabytes. For example, to cre‐
ate a split archive called foo with the contents of the bar
directory with splits of 670 MB that might be useful for burning
on CDs, the command:

                zip -s 670m -r foo bar

could be used.

So, to create a split zip archive, you could do the following (the "-r" is the "recursive" switch to include subdirectories of the directory):

$ zip -r -s 10m archive.zip directory/

To unzip the file, the "zip" manpage explains that you should use the "-s 0`" switch:

(...)

 zip -s 0 split.zip --out unsplit.zip

will convert a split archive to a single-file archive.

(...)

So, you first "unsplit" the ZIP file using the "-s 0" switch:

$ zip -s 0 archive.zip --out unsplit.zip

... and then you unzip the unsplit file:

$ unzip unsplit.zip