Skip to content

Instantly share code, notes, and snippets.

@jamesktan
Last active April 17, 2025 02:26
Show Gist options
  • Save jamesktan/5977349562e6f6cab9ea to your computer and use it in GitHub Desktop.
Save jamesktan/5977349562e6f6cab9ea to your computer and use it in GitHub Desktop.
Unzipping & Zipping ePub from Command Line
// 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)
@phoenixeliot
Copy link

Found some even more concise versions from the Ebooks StackExchange: https://ebooks.stackexchange.com/questions/257/how-to-repack-an-epub-file-from-command-line/7278#7278?newreg=ec07b030898d48868a88caec7809c255

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')

macOS: (you should change the epub name here to whatever it should be called)
zip -rX "../myprecious.epub" mimetype $(ls|xargs echo|sed 's/mimetype//g') -x *.DS_Store

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.

@mariocha
Copy link

great phoenixeliot but I had to remove the last part -x *.Ds_Store
because zsh: no matches found: *.DS_Store

@rohswell
Copy link

rohswell commented Jan 2, 2025

mariocha and phoenixeliot - Though I forget exactly where I found these commands, they work well for me.

zip -0Xq archive_name mimetype
-0 sets compression speed to zero, meaning no compression
-X exclude extra file attributes
This command puts the mimetype file into the zip archive first with no extraneous info.

zip -Xr9Dq archive_name *
-X exclude extra file attributes
-r recurse into directories
-9 compress better
-D do not add directory entries
Compresses all the other contents of the current folder into the archive. This works for EPUBs built with and without the OEBPS folder.

Because zip -h2 (long help) did not explain -D adequately, I found the Linux man page useful. If I read it correctly, -D doesn't create directories inside the zip archive for the purpose of saving directory attributes. This does not conflict with the recursion option, which I thought it did before I read the man page.

I found by experiment, that zip ignores dot files like (.) (..) and .DS_Store, so the -x *.DS_Store is not needed on MacOS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment