如何在Cron上动态设置变量? [英] How dynamically set variables on Cron?

查看:822
本文介绍了如何在Cron上动态设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将cron文件放置在/ etc / croon中。 d。我的问题是我不想保持此文件的更新,因此我正在寻找一种从文件动态获取软件版本的方法。
我没有几个其他变量,但是现在我认为问题出在 $(cat / software / VERSION),它在shell脚本中工作得很好,但没有

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 

这是cron日志的输出:

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


推荐答案

Cron表不是一个shell脚本!您不能在其中放置变量。

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

您必须从cron调用脚本并在其中执行逻辑。

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

如果确实必须在cron中设置环境变量,则可以这样做

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 

但这可能无法正常工作,您可能会犯一个错误(我不是100%确定我正确地配置了语法;这并不容易,也没有必要。)

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

您应该对cron尽可能少地添加逻辑。

You should put as little logic to cron as possible.

此外,您不应该直接编辑cron文件。使用 crontab -e 代替,它将检查您的语法是否正确。

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

所以您应该这样做

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

并在脚本中设置变量 。 (如果可能,您也不应以root用户身份运行程序。)

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

这篇关于如何在Cron上动态设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆