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
[root@server ~]# echo $?
[root@server ~]# pgrep crond123
[root@server ~]# echo $?
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 ; [ $? != 0 ] && /path/

The logic of this works by [ $? != 0 ] evaluating the return code of /usr/sbin/pgrep 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/ script based on a return code of 0 from [ $? != 0 ] (test statement).

About the Author


R Donato

Rick Donato is the Founder and Chief Editor of He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001