Checking file/directory existance before action

Cron is a great tool but it can get annoying when you get mail after mail because you neglected to think your cronjob through. One problem a lot of people have is that they just want to move, copy or delete files and/or directories in a quick command. The problem is that if the file(s) and/or directory doesn't exist cron will send out a mail because it thinks it may be an error (non-zero return code).

Checking if a file or directory exists is simple in bash with the “-f” or “-d” option. However, this will not work if you are looking for multiple files or directories. Below is an example of what a lot of people do which results in a cron error mail every time there is nothing to delete.

# Below works for shit
0 20 * * * rm /tmp/gs_*

Now let's take a look at how to do it correctly.

# Here is the correct way to do it
0 20 * * * if ls /tmp/gs_* &> /dev/null; then rm /tmp/gs_*; fi

Quit simple and still fits neatly on a short line. If there are any entries the return code will return “TRUE” and execute the remove. The redirect to /dev/null ensures that it's a clean execution and anything other than the return code is ignored. Enjoy.

/var/customers/webs/cw01/wiki/data/pages/cron/file_check.txt · Last modified: 2013/07/09 09:20 by wadmin
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki