I would like to use the unix zip command to zip a directory. Let's say the directory is structured as follows:

dir1/
dir1/dir2/
dir1/dir2/file1
dir1/dir2/file2
dir1/dir3
dir1/dir3/file1
dir1/file1
dir1/file2

I would like to zip dir1 into dir1.zip such that dir1.zip contains dir1/file1, dir1/file2, dir1/dir2/file1, dir1/dir2/file2, dir3/, but NOT dir1/dir3/file1. In short, I'd like to zip all of the FILES under dir1, dir2 and all of its files, and dir3 but NONE of its files.

If I do zip dir1 dir1/, it will zip everything in dir1, all of its files and subfolders but not the contents of the subfolders. If I do zip -r dir1 dir1/, it will zip everything in dir1, including all of its files and all of the files of its subfolders. I would like to be able to control which subfolders should be zipped recursively and which shouldn't.

Thanks.

  • It looks to me like you could use the -i option. Does that not work for you? – Faheem Mitha May 24 '11 at 19:24
$ zip -r dir1 dir1 -x dir1/dir3/*

works for me. Here -x is the exclude option. You could also use an include option, but in this case, the exclude option involves less typing.

Actually the question is not completely clear. Do you want all directories and files under dir3 excluded as well, or just the files under dir3? The command above only works for the latter.

One method to work with archive files is to mount them, and then access them like normal directories. FUSE is available for most unices and supports several filesystems to access compressed files transparently. For zip files, possibilities include fuse-zip (AVFS is also convenient but read-only).

For example, with fuse-zip, here's how to mount the archive and copy the files into it.

mkdir tmp
fuse-zip /path/to/zip tmp
rsync -av --exclude='/dir1/dir3/*' dir1 tmp/
fusermount -u tmp; rmdir tmp
  • Interesting approach. i know mc also has support for creating virtual filesystems for archives. – Faheem Mitha May 25 '11 at 9:20

Try this command from the parent directory of dir1:

tar --exclude=dir3/* -cf - dir1/ | zip dir1.zip -

And to unzip dir1.zip use this command:

unzip -p dir1.zip | tar xf -

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.