User Tools

Site Tools


Sidebar

js#vista.png msort nsort

cron:file_check

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.

cron/file_check.txt · Last modified: 2020/02/24 11:16 (external edit)