views:

347

answers:

3

I'm looking for a command that will compress every folder within a directory separately with the name of each archive reflecting the original folder name. I know that

tar czvf example.tar.gz example/

will compress an entire folder. However, I have not found a command to bulk archive. Is there such a command?

+1  A: 
find -mindepth 1 -maxdepth 1 -type d -exec tar czf {}.tar.gz {} \;

Note that I used -maxdepth 1.

Consider the directory structure:

.
|-- a
|   `-- x
|-- b
`-- c

Without -maxdepth 1 you would get a.tar.gz and a/x.tar.gz. a.tar.gz would contain x and all of the files within; and a/x.tar.gz would contain x and its files. But this stores the items within x twice, assuming that isn't the goal.

Updated to use -mindepth 1 as well, because when run outside of example/ an example.tar.gz would be created as well.

Update ... and for bzip2:

find -mindepth 1 -maxdepth 1 -type d -exec tar cjf {}.tar.bz2 {} \;
opello
Without -mindepth 1, won't it create an archive for the current directory?
Adam Crume
I thought that too, but when I tested it I didn't see that happening.
opello
Ah but if you execute it within "example/" it doesn't, if you don't, it does. Will update.
opello
is it possible to adjust the command so that bzip2 is used for compression?
undoIT
@opello: Since the find command is finding '.', wouldn't it create a file called '..tar.gz'? ls wouldn't show that by default.
Adam Crume
@undoIT: change 'tar czf' to 'tar cjf' and change the extension from '.gz' to '.bz2'. @Adam Crume: It doesn't seem to be the case, at least for me and findutils 4.4.0.
opello
+1  A: 
for f in `find -mindepth 1 -maxdepth 1 -type d`; do
    tar -czf $f.tar.gz $f
done
Adam Crume
Thanks! Exactly what I was looking for.
undoIT
Okay, one more question. If I want to compress to bzip2, what would the full command be?
undoIT
A: 

Okay, here's the final command I came up with to archive then compress with bzip2 for maximum compression

find -mindepth 1 -maxdepth 1 -type d -exec tar cjf '{}'.tar.bz2 '{}' \;

thanks everyone!

undoIT