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

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?



Solution 1:[1]

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
 

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dudi Boy
Solution 2 Fravadona