[linux] Create zip file and ignore directory structure

I need to create a zip file using this command:

zip /dir/to/file/newZip /data/to/zip/data.txt

This works, but the created zip file creates a directory structure mimicking the directory to the raw file. It is a lot of extra folders that I don't need.

I didn't find an answer in a cursory glance over the man page or a Google hunt.

This question is related to linux zip

The answer is


Retain the parent directory so unzip doesn't spew files everywhere

When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;

The ../$(basename $PWD) is the magic that retains the parent directory.

So now unzip my.zip will give a folder containing all your files:

parent-directory
+-- file1
+-- file2
+-- dir1
¦   +-- file3
¦   +-- file4

Instead of littering the current directory with the unzipped files:

file1
file2
dir1
+-- file3
+-- file4

Somewhat related - I was looking for a solution to do the same for directories. Unfortunately the -j option does not work for this :(

Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file


Use the -j option:

   -j     Store  just the name of a saved file (junk the path), and do not
          store directory names. By default, zip will store the full  path
          (relative to the current path).

Just use the -jrm option to remove the file and directory structures

zip -jrm /path/to/file.zip /path/to/file

Alternatively, you could create a temporary symbolic link to your file:

ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$

This works also for a directory.


Using -j won't work along with the -r option.
So the work-around for it can be this:

cd path/to/parent/dir/;
zip -r complete/path/to/name.zip ./* ;
cd -;

Or in-line version

cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -

you can direct the output to /dev/null if you don't want the cd - output to appear on screen