Thursday, May 20, 2010

Zip or War All Directories in Current Directory into Individual Zip or War Files

If you need to zip or war all of the directories only in the current directory into their own zip or war files, here are a few approaches:

To zip all of the directories only in the current directory into individual zip files and retain the directory name in the zipped files so that when they expand they expand back into that directory, just use:

find * -prune -type d -exec zip -r "{}.zip" "{}" \;
But if you want to zip or war each so that you change directories (you change the current directory/working directory such that when the zip expands, it expands the files and directories of that directory into the current directory, as you would expect in a war file), you can't just use "cd" in the exec, and the unix zip command doesn't appear to let you change the working/current directory. The easiest thing to do is to have a separate shell script that changes the current working directory and does the zip.

Create a file called warit.sh or zipit.sh and put it on the path.

zipit.sh:

#!/bin/bash
set -e
cd $1
zip -r "../$1.zip" .

warit.sh:

#!/bin/bash
set -e
cd $1
jar cvf "../$1.war" .
then just:
find * -prune -type d -exec zipit.sh {} \;
or
find * -prune -type d -exec warit.sh {} \;
and it will cd into each of the directories, zip all that up, and place the resulting zip or war into the parent directory. This is basically a hack for zip not taking an argument to specify the working directory, and because cd has difficulties running within find's exec. I fought this a good while and would appreciate if someone has a more elegant solution or could fight to allow the OS X 10.6.3 zip command to specify the current working directory.

Instead of "find * -prune -type d -exec ...", you can also use "find . -d 1 -type d -exec ...".

No comments: