20

I can use -s in grep to suppress errors, but I don't see an equivalent for the find command in the man page... Is the only option to redirect STDERR>/dev/null?

Or is there an option that handles this? (open to fancy awk and perl solutions if needed)

Example:

$ for dir in `ls /mnt/16_c/`; do find /mnt/16_c/$dir/data/ -mtime +180 -type f -exec echo {} \;; done
find: `/mnt/16_c/test_container/dat/': No such file or directory
JacobIRR
  • 8,545
  • 8
  • 39
  • 68
  • What's wrong with redirecting stderr? Why do you want to use external tools like awk and perl? Without knowing what's the problem, it's difficult to propose solutions – Andrea Corbellini Aug 08 '17 at 17:59
  • 2
    You could test if the directory exists before calling find `test -d /mnt/16_c/$dir/data/ && find ....` so no need to redirect at all – Stefan Hegny Aug 08 '17 at 19:59

2 Answers2

24

You can redirect stderr with 2>/dev/null, for example:

find /mnt/16_c/$dir/data/ -mtime +180 -type f -exec echo {} \; 2>/dev/null

Btw, the code in your question can be replaced with:

find /mnt/16_c/*/data/ -mtime +180 -type f 2>/dev/null

And if there is at least one matching directory, then you don't even need to suppress stderr, because find will only search in directories that match this pattern.

janos
  • 120,954
  • 29
  • 226
  • 236
4

I know this isn't exactly what you asked, but my typical approach is to find a path that definitely exists, then use the -path flag to filter.

So instead of find /home/not-a-path, which raises an error, I would do find /home -path "/home/not-a-path/*", which doesn't raise an error.

I had to do this because when I would stream a failed find to /dev/null in a make file, the error would still cause the command to crash. The approach I described above works though.

Praveen Lobo
  • 6,956
  • 2
  • 28
  • 40
fenix
  • 169
  • 1
  • 4