Conditional Execution within Crontab

Conditional execution is a term used to describe the execution of processes or commands based on specfic conditions. This can also be thought of as conditional logic. 
Like with most scripting or programming languages conditional logic is built upon the use of return codes. A return code (exit status)  is returned upon process completion to determine success or failure. A return code of 0 is set if the process has been successfully executed, and a non-zero is set on failure.

You can test this by running a command such as pgrep crondon a system that you already know is running crond.

[root@server ~]# pgrep crond
2518
[root@server ~]# echo $?
0
[root@server ~]# pgrep crond123
[root@server ~]# echo $?
1

The $? allows you to echo the return code. In this case crond was successful but crond123 was not as there is no process running with this name.
Using this logic we can create a single crontab entry to allow us to run a script only if it is not already running.

* * * * *  /usr/sbin/pgrep example.sh ; [ $? != 0 ] && /path/example.sh

The logic of this works by [ $? != 0 ] evaluating the return code of /usr/sbin/pgrep example.sh. If this evaluation is successful (i.e a return code of 0 is not found from the pgrep command) then a return code of 0 is produced from this test statement. The test statement return code is then passed to &&. && works by only executing any further commands if a return code of 0 is received. This then allows us to only run the /path/example.sh script based on a return code of 0 from [ $? != 0 ] (test statement).

Rick Donato

Want to become a Linux expert?

Here is our hand-picked selection of the best courses you can find online:
Linux Mastery course
Linux Administration Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial