0

I want to compress (tar or gzip or zip) directories older than two days. I have the files below. Each directory will have multiple subdirectories and files.

Oct 21 13:01 test1
Oct 22 13:01 test2 

Desired output:

   test1.tar
   test2.tar

I tried writing the command, below; but, it is not working.

   find . -type d -maxdepth 1 -mtime +2 \! -name '*.gz' -exec gzip {} \;

I am getting the below error.

   gzip:test1.tar is a directory -- ignored
   gzip:test2.tar is a directory -- ignored
  • 1
    Like the man said : gzip, gunzip, zcat - compress or expand files – Gilles Quenot Oct 23 '17 at 15:26
  • I tried running this script but it is not working..what is wrong with j=find $dir -maxdepth 1 -type d -mtime -2 echo "$j" for i in "$j" do [ -d "$i" ] && zip -r "$i.zip" "$i" done – Naresh Oct 23 '17 at 15:28
1

Because gzip can ONLY compress files, you first must tar the directories prior to gzipping them.

What you want to do is use GNU tar with "z", "z" compresses:

find . -type d -maxdepth 1 -mtime +2 \! -name '*.gz' -exec tar cfz {}.tgz {} \;

EDIT After Comment:

I had not paid attention to \! -name '*.gz', which under normal circumstances is superfluous ... provided you have no directory names ending in .gz.

find . -type d -maxdepth 1 -mtime +2 -exec tar cfz {}.tgz {} \;

  • I will try this – Naresh Oct 23 '17 at 15:32
  • 1
    @Naresh: I would add -mindepth 1 to avoid packing .. \! -name '*.gz' is redundant since you filter for directories - unless you have and want to ignore directories name *.gz. – sborsky Oct 23 '17 at 16:08
0

Use tar archiving utility:

find . -type d -maxdepth 1 -mtime +2 ! -name '*.gz' -exec tar -czvf old_dirs.gz '{}' +;

-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files.

  • Nice example for +, however, op wanted test1.tar and test2.tar, not all_dirs.gz. – thecarpy Oct 23 '17 at 16:20

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.