1

find /var/log/myfile.*.txt -type f

If no file is present matching that pattern, I'm getting error logs like No such file or directory.

Question: how can I prevent only this error message? I could of course add a 2>/dev/null at the end, but that would suppress any errors. How could I just ignore the one mentioned?

Because I have a cronjob that deletes some files periodically, and always logs errors if no file was present:

@daily find /var/log/myfile.*.txt -mtime +7 -delete

1 Answers1

3

The right thing in this case is not to trigger this message at all.

When you run this in a shell

find /var/log/myfile.*.txt -type f

/var/log/myfile.*.txt is expanded by the shell; find gets expanded object(s) or literal /var/log/myfile.*.txt if there is no match. The latter case triggers No such file or directory.

You can create a dummy file first: touch '/var/log/myfile.dummy_name.txt' (compare elephant in Cairo). This "solution" is not really elegant though.

A better solution is to make find handle the pattern:

find /var/log/ -type f -name "myfile.*.txt"

where double-quotes prevent globbing in the shell (compare this). In this case * is handled by the find itself because -name supports such patterns.

The above approach however can match myfile.*.txt in any subdirectory of /var/log/ as well. If your find supports -maxdepth, use it:

find /var/log/ -maxdepth 1 -type f -name "myfile.*.txt"

If not, see this: Limit POSIX find to specific depth?


Your OS probably already uses logrotate(8) to manage logfiles.

In my Debian logrotate runs daily because of /etc/cron.daily/logrotate; it should be similar in Ubuntu. I can create a custom config in /etc/logrotate.d/ and manage arbitrary logfiles this way. Consider this approach.