Piping output to text file within a for loop

filesforkshpipe

I'm trying to do the following within a for loop:

  • Find files that satisfy a condition
  • Echo the name of the files to a log file.
  • Gzip the file.

I can get the script to find the files and echo their names to the screen but cannot pipe them to a file.
(I have not got as far testing the gzip part)

Here's the relevant portion of the script (The $LOGCLEAN_FILE exists and is written to in an earlier portion of the script):

for F in `find . -type f \( ! -name '*.gz' \) -a \( ! -name '*.Z' \) -mtime +7`
do

        {
        print "Will be compressing file  ${F}" >> $LOGCLEAN_FILE
        } ; 
        ##gzip $F
done

If I run the script without the " >> $LOGCLEAN_FILE" text then the output displays on the screen.

What am I doing wrong?

Criticisms are welcome – I'm still learning.

Best Answer

There really is no need for reproducing find's output ina shell loop. If you want to pack the list of filenames, the generic formula is:

find ... | gzip > logfile.gz

If you want to gzip the files themselves, it changes to:

find ... | tar -czvf archive.tar.gz -T -

which tells tar to read list of file names to work on from a file and the single - stands for standard input. (The -T AKA --files-from= option is present in GNU tar, I'm not sure about other flavours.) Of course this breaks if you manage to work on files which contain \n in their names.

Related Question