{"id":531,"date":"2011-03-09T09:47:26","date_gmt":"2011-03-09T09:47:26","guid":{"rendered":"https:\/\/fir3netwp.gmsrrpobkbd.com\/2011\/03\/09\/conditional-execution-within-crontab\/"},"modified":"2021-07-24T18:33:39","modified_gmt":"2021-07-24T18:33:39","slug":"conditional-execution-within-crontab","status":"publish","type":"post","link":"https:\/\/www.fir3net.com\/UNIX\/Linux\/conditional-execution-within-crontab.html","title":{"rendered":"Conditional Execution within Crontab"},"content":{"rendered":"
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. <\/p>\n
You can test this by running a command such as pgrep crond<\/span>on a system that you already know is running crond.<\/p>\n The $?<\/span> allows you to echo the return code. In this case crond<\/span> was successful but crond123<\/span> was not as there is no process running with this name. The logic of this works by [ $? != 0 ]<\/span> evaluating the return code of \/usr\/sbin\/pgrep example.sh<\/span>. 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 &&<\/span>. &&<\/span> 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 ] <\/span>(test statement).<\/p>\n","protected":false},"excerpt":{"rendered":" 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 … Read more<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[52],"tags":[],"yoast_head":"\n[root@server ~]# pgrep crond
2518
[root@server ~]# echo $?
0
[root@server ~]# pgrep crond123
[root@server ~]# echo $?
1<\/pre>\n
Using this logic we can create a single crontab entry to allow us to run a script only if it is not already running. <\/p>\n* * * * * \/usr\/sbin\/pgrep example.sh ; [ $? != 0 ] && \/path\/example.sh<\/pre>\n