【问题标题】:Environment Variables inside the container, but not used in the bash script容器内的环境变量,但未在 bash 脚本中使用
【发布时间】:2022-11-27 13:09:44
【问题描述】:

我有一个在 docker 容器内运行的应用程序。首先我构建图像然后运行容器。我的运行命令是:

docker run --rm -it -e MODE=custom -e Station=RT -e StartDateReport=2022-09-10 -e Period=1 my-image:1.0.0

我将变量MODE, Station, StartDateReport and Period 声明为环境变量。当我从容器启动终端并输入echo $MODE时,我将得到正确的值custom

到目前为止一切顺利,但我有兴趣在bash script 中使用这些变量。例如在start.sh我有以下代码:

#!/bin/bash

if [[ $MODE == custom ]]; then
   // do sth
fi

在脚本中,我的变量MODEundefined,因此我得到了错误的结果。

【问题讨论】:

  • docker 中没有什么特别之处可以改变 bash 的行为。您是否尝试过使用引号:"$MODE" == "custom"-eq 运算符?
  • 你如何开始start.sh?你在docker中启动它吗?
  • 我使用定时任务。 * * * * * cd /app/ && bash start.sh >> /var/log/cron.log &.我相信这是问题所在,@KamilCuk。我显然没有声明用于执行脚本的变量。
  • 我不明白。那么 docker 与 cronjob 有什么关系呢?您的 docker 测试与 cronjob 有何关系?
  • 我想在特定时间段运行我的应用程序。 start.sh 是起点,也是应该运行的第一件事。 * * * * * cd /app/ && bash start.sh >> /var/log/cron.log & 刚刚启动 start.sh,在这种情况下,每分钟一次。

标签: bash docker shell


【解决方案1】:

在您的环境中,您的变量定义是否具有以下形式

export MODE="custom"

脚本的修改版本:

#!/bin/bash

test -z "${MODE}" && ( echo -e "
	  MODE was not exported from calling environment.
" ; exit 1 )

if [[ $MODE == custom ]]
then
    #// do sth
    echo "do sth"
fi

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多