How dynamically set variables on Cron?

假装没事ソ 提交于 2019-12-11 06:59:44

问题


I'm trying to make a cron file to be placed in /etc/croon. d. My problem is I don't want keep this file updated, so I'm looking for a way to get the software version dynamically from a file. I have few other variables, but for now I think the problem is with $ (cat /software/VERSION), it works very well in shell script but not on croon.

#!/bin/bash
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
APPLICATION_ENVIRONMENT=SOME_STRING
VERSION=$(cat /software/VERSION)
HOME=/var/www/scripts/$VERSION/cron
CRON_LOG_DIR=/var/www/scripts/logs

*/2 *   *   *   *   root    cd  $HOME & php -f $HOME/do_something.php $APPLICATION_ENVIRONMENT  >> $CRON_LOG/something.log 

This is the output on cron log:

(root) CMD (cd  $HOME & php -f $HOME/do_something.php $APPLICATION_ENVIRONMENT >> $CRON_LOG/something.log)
(CRON) ERROR chdir failed (/srv/www/tdp/public/$VERSION/backend/cron): No such file or directory

回答1:


Cron table is not a shell script! You cannot put variables there.

You have to call a script from the cron and do the logic there.

If you really have to set environment variables in cron, you can do it like this

*/2 *   *   *   *   root    SHELL=/bin/bash VARIABLE=something cd  $HOME & php -f $HOME/do_something.php $APPLICATION_ENVIRONMENT  >> $CRON_LOG/something.log 

But it might not work and you might make a mistake (I am not 100% sure I made the syntax right; it's not easy and it's not necessary).

You should put as little logic to cron as possible.

Also, you should not edit the cron file directly; use crontab -e instead, it will check if you made correct syntax.

So you should do

*/2 *   *   *   *   user    /home/user/your-script.sh

and set the variables in your script. (You also shouldn't run programs as root if it's possible.)



来源:https://stackoverflow.com/questions/42843514/how-dynamically-set-variables-on-cron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!