How do I zip a folder without including all folders in the path?

I am attempting to zip a website's home directory but the archive contains the entire path of folders before getting to the one to be zipped. The command zip -r compressed_data.zip /home/vivek/public_html results in compressed_data.zip containing home->vivek->public_html rather than simply public_html and its contents.

What switch can I add to the command to omit including all folders in the path?


Solution 1:

By default, the zip process will store the full path relative to the current directory, so if you want to have an archive that looks like this:

/config
/files
/lib
.htaccess
index.html

Then you will need to be in public_html to begin with. That said, you can account for this with a one-liner:

cd /home/vivek/public_html && zip -r ~/compressed_data.zip . * ; cd -

This will change directories, compress the contents, then return you to the home directory.

If you would like to do this as part of a script that is called via a cronjob or other process, create a file like this:

#!/bin/bash
dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
(cd "/home/vivek/public_html" && zip -r "${dir}/compressed_data.zip" ./*)

You can read more about the limits of zip from its manual page 👍🏻