how to repack an epub file from command line

September 9, 2018 - Reading time: 5 minutes
To unzip the epub, move the ePub to a folder, cd to it then simply:
unzip MyEbook.epub
To zip up an epub:
1. zip -X MyNewEbook.epub mimetype
2. zip -rg MyNewEbook.epub META-INF -x \*.DS_Store
3. zip -rg MyNewEbook.epub OEBPS -x \*.DS_Store
Some explanations necessary here. We start each line with two flags:
-r (recursive)
This means move down through any directories/folders recursively, ensuring that everything in the folders specified gets included
-g (grow file)

even more concise :
// To unzip the epub, move the ePub to a folder, cd to it then simply:
zip -rX ../my.epub mimetype META-INF/ OEBPS/

Without -X you could get the following when validating it with EpubCheck:

ERROR: my.epub: Mimetype entry must not have an extra field in its ZIP header

If mimetype is not the first in the epub file EpubCheck prints the following:

ERROR: my.epub: Mimetype entry missing or not the first in archive

Linux uses the name of the current folder as the epub filename:
zip -rX "../$(basename "$(realpath .)").epub" mimetype $(ls|xargs echo|sed 's/mimetype//g')

I found this version also worked better for epubs I found that don't use the OEBPS folder. I don't know if not having that folder is valid per standards, but I found examples of it being missing in the wild.