• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 208
  • Last Modified:

How would i gzip every direcory within a directory and then list its size


Lets say i have my top level directory and these have subdirectories called dir1, dir2, dir3 etc. These subdirectories can in turn have subdirectories.

I would like a command which will gzip every directory in my current working directory. I am hoping this will zip any subdirectories therein. The name of the zipped top level directory can simply be the name of the original directory appended with .gz

I've seen this but this will zip and the directories and create a tar acrhive?
tar czvf mytar.tar.gz dir1 dir2 .. dirN

What if i just want to gzip the files and not create the tar file?
2 Solutions
I don't believe that gzip works on directories.  It's why we use tar with options to compress.  You should use tar for tar'ing up the directories and use the z option to gzip the archived directories.  Use j if you want to bzip them for better compression.

cd top_level;  for i in * ; do tar czf $i  $i.tgz; done

cd top_level;  for i in * ; do tar cjf $i  $i.tar.bz; done

If you want to gzip the files in every subdirectory individually, you could use find.

find . -name "*" -exec gzip {} \;

I think this will also delete the original file when the .gzipped version is created.

gzip * will gzip all the files in the current directory.
gzip only works on individual files.

If you want to create a compressed archive of directories and multiple files, then you need to either tar/compress, or use zip.
SurranoSystem EngineerCommented:
addition to serialband's comment: tar first filename param should be the archive file  and the rest should be the files to archive. Dropping in some tricks to
- archive dirs only (not single files),
- including hidden ones
- removing the source, i.e. emulate what gzip does

for d in */ .[^.]*/; do 
  tar czf $d.tgz --remove-files $d
  ls -l $d.tgz

Open in new window


Thanks for catching that.  I typed those after a 12 hour work day doing an "after hours" server upgrade/transition.
andiejeAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now