【问题标题】:Can CRON job pass the updated value of existing environment variable to a shell script?CRON 作业可以将现有环境变量的更新值传递给 shell 脚本吗?
【发布时间】:2022-01-23 12:37:46
【问题描述】:

这是我的 cron 脚本:* * * * * /script.sh >> /var/log/script.log

我的 script.sh 文件

'''

#!/bin/sh

env
echo $DISABLE_CACHE

if [ "$DISABLE_CACHE" = "true" ]
then
    echo " RELOADING NGINX "
else
    echo "Routine cron job"
fi

'''

所以当 cron 作业开始时,DISABLE_CACHE 变量值被设置为 true。 它是一个字符串变量,不是布尔值。

但是现在,当我由于某些要求故意将 DISABLE_CACHE 变量值更改为 false 时,我可以通过从终端触发“env”命令来查看 cron 脚本之外的更改。

但在 cron 作业中,它仍然会在我的 /var/log/script.log 文件中打印旧的 env 值。

知道我的 cron 作业如何获取现有环境变量的更新值吗?

仅供参考:

我在 alpine docker 容器中尝试的整个设置

【问题讨论】:

  • 每个进程都有自己的环境。在一个进程中更改环境变量不会影响其他进程(如 cron 作业)。 (例外:分叉的子进程获取父进程环境的副本。但 cron 作业是从 crond 中分叉的,而不是您的 shell 进程。)
  • 感谢您的回复。那么这种情况就没有办法解决了吗?
  • 你应该在某个文件中写入一些东西,也许在 /var/run/...

标签: bash docker cron alpine


【解决方案1】:

您可以使用文件。我将 disable_cache 更改为小写。

#!/bin/bash
env
nginx_cache=/etc/nginx_cache
test -f "${nginx_cache}" && disable_cache=$(<"${nginx_cache}")
echo "$disable_cache"

if [ "$disable_cache" = "true" ]
then
    echo " RELOADING NGINX "
else
    echo "Routine cron job"
fi

现在您可以使用 echo "true" &gt; /etc/nginx_cache 更改脚本之外的设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2015-09-09
    • 2021-01-21
    • 1970-01-01
    • 2011-09-18
    • 2018-02-06
    相关资源
    最近更新 更多