How to zip a folder using the command line while maintaining its file structure

terminalzip

For example, if I want to zip /Users/admin/Downloads/Backup, and I am at /Users/admin/, I could:

zip -r downloads.zip /Users/admin/Downloads/Backup

and if I unzip downloads.zip I would get a Users folder and have a Users => admin => Downloads => Backup structure.

This is particularly undesirable behavior if I want to create an installation zip file for TWRP.

So instead I will have to:

cd /Users/admin/Downloads/Backup; zip -r /Users/admin/downloads.zip .; cd /Users/admin/

This doesn’t feel like what a pro would do.

What can I do to zip a folder while maintaining its file structure?

Best Answer

A "pro" would first read the manual. Now, the zip manual is full of cruft but long into the read you'll find- " zip will store the full path (relative to the current directory).". Further into the read you will find an option to remove all paths in your zip archive but that is not a great idea, since you can create a "bomb" archive that will pollute the directory in which it is extracted. It's best to contain your archive within its own directory.

cd /Users/admin/Downloads
zip -r downloads Backup
mv -- downloads.zip some/other/location
cd -
  • First we change directory to /Users/admin/Downloads
  • We name the archive (downloads) and .zip will be added to the archive name
  • We recurse through the Backup directory adding all files including the parent directory to the archive
  • move the zip archive to another location
  • Finally, we call the environment variable OLDPWD to get back to the original directory- cd -