Several exec on find send all the output to the last redirection

Example script:

 find mydir -type f -exec echo {}>aaa \; -exec echo {}>bbb \;

The two paths go the the bbb file, while there should be one of them on each file. How should I do it to get it working?

One way:

find mydir -type f  | tee -a aaa > bbb

You do not need echo, find prints by default.

1 Like

The reason is that >aaa and >bbb are handled by the shell.
While it does not matter where you place them, one usually places them at the end.
So your code is identical to

find mydir -type f -exec echo {} \; -exec echo {} \; >aaa >bbb

The tee (or a further descriptor) makes aaa and bbb identical - probably not what you intended.

---------- Post updated at 03:16 PM ---------- Previous update was at 02:07 PM ----------

Probably you want something like this:

find . -type f -exec sh -c 'echo "$1" >>files' sh {} \; -o -type d -exec sh -c 'echo "$1" >>directories' sh {} \;

Because -print is far more efficient and there are likely more files than directories, the following should be more efficient:

>directories #rewrite
find . -type f -print -o -type d -exec sh -c 'echo "$1" >>directories' sh {} \; > files
2 Likes