I have around 200 folders right under a huge folder Parent, say as child1-100




How do I change all the folders named child 1-100 into each zip folder, such as child1.zip, child2.zip? I tried doing this command for i in */; do zip -r "${i%/}.zip" "$i"; done but it gave me child1.zip which after extracted gave /child1/child1/contents. I just want the zip file child1.zip to give /child1/contents folder after extracting.

  • Your code looks correct. You say "extracted gave /child1/child1/contents" -- what directory were you in when you extracted? The zip file will contain "child1/contents", verify with unzip -l child1.zip. If you did cd child1; unzip ../child1.zip then you will get the results you see. – glenn jackman May 1 '18 at 1:14

If you want the zip file to contain only contents, not child1/contents, then do this:

for dir in */; do
    ( cd "$dir" && zip -r ../"${dir%/}".zip . )
  • That worked like a charm. Could you please explain what I was missing? – stackFan May 1 '18 at 1:55
  • since zip preserves the directory structure, when you zip -r x.zip dir, the zip contains files named dir/file1, dir/file2, etc. If you don't want to keep that top level of the hierarchy, you need to descend into the directory. – glenn jackman May 1 '18 at 3:02
for dir in child*; do
    #recursive zip to include folder contents
    zip -r "${dir}.zip" "$dir"
  • You should quote $dir whenever you use it. – Chris Apr 30 '18 at 23:41
  • It did not work, it just changed child1 to an empty zip folder. – stackFan Apr 30 '18 at 23:43
  • zip -r would recursively add the contents of the directories – Jeff Schaller Apr 30 '18 at 23:59
  • 1
    @JeffSchaller is correct on this one Add the -r to the zip command and it will work properly. The first command will just make a .zip of the folder name. @DopeGhoti had the right idea! – saleetzo May 1 '18 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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