How to auto zip all folders?

Hi,

How do I write a script that will automatically find and zip any folder to the same name in a directory and affected recursively?. The zip file should be place in the same directory where the source folder is. Help is appreciated. Thanks in advance.

ex:

Orange Crayon
Blue Crayon
Red Box

to

Orange Crayon.zip
Blue Crayon.zip
Red Box.zip

Welcome Frozen77,
I have a few to questions pose in response first:-

  • Is this homework/assignment? There are specific forums for these.
  • What have you tried so far?
  • What output/errors do you get?
  • What OS and version are you using?
  • What are your preferred tools? (C, shell, perl, awk, etc. along with gzip or other compression software)
  • What logical process have you considered? (to help steer us to follow what you are trying to achieve)

Most importantly, What have you tried so far?

There are probably many ways to achieve most tasks, so giving us an idea of your style and thoughts will help us guide you to an answer most suitable to you so you can adjust it to suit your needs in future.

We're all here to learn and getting the relevant information will help us all.

Robin

This is not a homework assignment. It's for my own site. I have a code that does similar things but only zip file not folders:

find . -type f -name '*.mp[4g]' -o -name '*.mkv'| while read -r path
do      base="${path%.*}"
        zip "$base" "$path"
done

Not sure how can I modify it to zip folders not files. I'm using CentOS 6.5.

Hello, please try this command in your source directory and let us know if it meets your requirement.

find . -maxdepth 1 -type d ! -name ".*" -exec bash -c 'zip -r "$0.zip" "$0"' {} \;
1 Like

junior-helper,

That seems to work, thanks alot. I have to ask does maxdepth mean it only search for 1 layer of subdirectory? how can it search infinite recursively? thanks again.

You're welcome.

Exactly.

Just remove the option -maxdepth 1

*** Important note **: Actually, the provided command is a combination of two commands (find+zip),
which *does
recursively zip. The recursively part is performed by the zip's option -r .

Assuming following directory structure

sourcedir/dir 1/sub dir A/sub sub dir B/sub sub sub dir C/
sourcedir/dir 2/sub dir 1/sub sub dir 2/
sourcedir/dir 3/sub-dir-x/sub-sub-dir-y/sub-sub-sub-dir-z/

and the command being run in the sourcedir, it would produce 3 zip files:

/sourcedir/dir 1.zip # (incl. all sub dirs of dir 1)
/sourcedir/dir 2.zip # (incl. all sub dirs of dir 2)
/sourcedir/dir 3.zip # (incl. all sub dirs of dir 3)

I highly doubt you want to remove the maxdepth option, because it would create a backup of the backup of the backup of the backup...

Hope you get the idea :slight_smile:

Edit:
You could add the echo command to just see what would happen, and afterwards remove the -maxdepth 1 part and see the difference.

find . -maxdepth 1 -type d ! -name ".*" -exec bash -c 'echo zip -r "$0.zip" "$0"' {} \;
2 Likes