How dynamically set variables on Cron?

2019-07-29 21:35发布

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条回答
在下西门庆
2楼-- · 2019-07-29 22:18

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.)

查看更多
登录 后发表回答