Shell command to loop and zip dir contents

You’ve got a list of directories and you’d like to zip only what’s inside it, keeping the directory name as the zip filename:

for d in */; do ( cd "$d" && zip -r "../${d%/}.zip" "./" ); done

You could instead:

for d in */; do cd "$d" && zip -r "../${d%/}.zip" "./" && cd ..; done

Starts by doing a for each directory, cd into it, compress recursively in the dir, name the file by the dirname moving it up to the parenth directory! Then cd back to initial position!

Some people would say this is a better practice:

find . -maxdepth 1 -mindepth 1 -type d -exec sh -c 'cd $(basename {}) && zip -r ../$(basename {}).zip .' \;

This one is even better, if you have 7z:

find . -maxdepth 1 -mindepth 1 -type d -exec 7z a -tzip {}.zip -w {}/. \;

find all in current dir that is type directory, but we let find know that we want to stay in the same position from where we executed the command. Finally we say to find exec this command for us, to zip the files and name it accordingly to what he found “{}”!

That’s it!

comments powered by Disqus