find -exec - suppress errors only for find, but not for executed command

Viewed 87

When running the find command, it may output "No such file or directory" errors.

As answered to the find - suppress "No such file or directory" errors question here: https://stackoverflow.com/a/45575053/7939871, redirecting file descriptor 2 to /dev/null will happily silences error messages from find, such as No such file or directory:

find yada-yada... 2>/dev/null

This is perfectly fine, as long as not using -exec to execute a command. Because 2>/dev/null will also silence errors from the executed command.

As an example:

$ find /root -exec sh -c 'echo "Error" >&2' {} \; 2>/dev/null
$ find /root -exec sh -c 'echo "Error" >&2' {} \;
Error
find: ‘/root’: Permission denied

Is there a way to silence errors from find while preserving errors from the executed command?

2 Answers

Using -exec option in find command is integration of xargs command into find command.

You can alwayes separate find from -exec by piping find output into xargs command.

For example:

 find / -type f -name "*.yaml" -print0 2>/dev/null | xargs  ls -l
 

If for some reason you can't use:

find . -print0 2>/dev/null | xargs -0 ...

Then here's a POSIX way to do the same thing:

find . -exec sh -c '"$0" "$@" 2>&3' ... {} + 3>&2 2>/dev/null

note: 3>&2 is located before 2>/dev/null

Related