Redirect find output to file

Hi,

I am trying to use the find command to redirect the output to file as follows:

find $HOME -name "newreport_*" -type d -print >> filesCleanedUp.txt -exec rm -rf {} \;

The section:

-print >> filesCleanedUp.txt

is supposed to do the re-direct, but it doesn’t seem to be working.

Any help greatly appreciated.

/jlar

The -print code is OK. You’ll see if you leave out the part after …txt. The redirect will be made instantly, the foldernames will be in the file.

You can only redirect the output of a command. The redirect (something you want to tell to bash, not to find!) must be AFTER the command. You can not put it somewhere beteen the parameter fields of the find command.

find $HOME -name "newreport_*" -type d -print -exec rm -rf {} \; >>filesCleanedUp.txt

will add all the standard output of the find command to the file* filesCleanedUp.txt*

But would you believe that you can also have it before the command? It’s due to the way the shell parses the various pieces of the line. In fact something as strange looking like this does work.

> foobar < /etc/issue cat

Guaranteed to confuse the heck out of anybody reading the script. So let’s not confuse the poor guy. :slight_smile: Just remember to put the redirection outside the command.

Hi everyone,

Thanks for all the replies…

I did try it like that already:


find $HOME -name "newreport_*" -type d -exec rm -rf {} \; >> filesCleanedUp.txt

as that is the way nearly every UNIX command redirects, but it doesn’t work. That’s why I changed to -print >> filesCleanedUp.txt Is it possible that nothing after ; is processed?

/jlar

You have to dig deeper into the man page to understand. Find takes a logical expression. The implied connector is -a (AND). So the above is equivalent to: (by the way you also need to escape {})

find $HOME -name "newreport_*" -a -type d -a -exec rm -fr '{}' \; -a -print

Now the success of the -exec clause depends on the command. The command may or may not return success. So you are probably better off swapping the last two expressions and putting the -print first.

I politely, but strongly recommend not to say “it does not work”, but explain what happens: see nothing, output going to the terminal, filesCleanedUp.txt empty after trial, red ball in the sky, … In short (computer ) facts, not stories.

the \ in ; is there for escaping it to the shell, such that it is delivered as a parameter field to find. In other words, it is there to prevent what you are afraid of.
What happens if you do not have the redirection? As we still do not know what happens when you have the redirection, is there a difference bewteen the two?

I’m such a wally… the reason this didn’t appear to ‘work’, was that there was nothing found by the ‘find’ command. Of course it’s not going pipe anything to file if there was nothing to pipe.

Thanks everyone for their helpful comments.

/jlar