【问题标题】:How to compare a variable and set the value in alpine linux [duplicate]如何在alpine linux中比较变量并设置值[重复]
【发布时间】:2020-01-21 05:24:23
【问题描述】:

之前从未编写过任何 shell 脚本,但在广泛使用谷歌搜索之后,我为我的 docker 文件想出了以下代码。但不明白为什么它不起作用。

###stage 2####################
FROM nginx:alpine

##########Calculate the environment type #########
ARG BUILD_TYPE

####echo of build build_type does gives me output of Development when passed argument is Development.
RUN if [ "$BUILD_TYPE" = "Development" ]; then BUILD_TYPE='dev'; fi
RUN if [ "$BUILD_TYPE" = "Production" ]; then BUILD_TYPE='prod'; fi
RUN echo "UI BUILD_TYPE=$BUILD_TYPE---------"
##########Calculate the environment type #########

上面的回声总是作为发展而来的。

更新

现在我在一个单独的 docker 文件中构建了一个示例来隔离问题。在此之后,我意识到尽管条件匹配,但任务并没有发生。

这是新的示例 docker 文件代码。

FROM nginx:alpine

ARG BUILD_TYPE
ARG ENV_TYPE

RUN if [ "$BUILD_TYPE" = "Development" ]; then ENV_TYPE='dev'; echo "matched dev"; fi
RUN if [ "$BUILD_TYPE" = "Production" ]; then ENV_TYPE="prod"; echo "matched prod"; fi
RUN echo "UI BUILD_TYPE=$BUILD_TYPE ENV_TYPE = $ENV_TYPE---------"

输出是

  1. 匹配的开发人员
  2. UI BUILD_TYPE=开发 ENV_TYPE = ---------

我看到 ENV_TYPE 是空的。

【问题讨论】:

  • 我觉得这个问题和stackoverflow.com/a/43656644/6284644是一样的
  • @coolcake:请明确要求:您说您想编写一个 POSIX shell 脚本,但是您用 bash 标记了这个问题。如果您需要 POSIX 兼容性,请将此标记替换为 shell
  • @coolcake :另外,将 docker 标签添加到这个问题中是有意义的。

标签: shell docker alpine


【解决方案1】:

Dockerfile 中的每个 RUN 命令都在单独的 shell 会话中执行,因此当您设置 BUILD_TYPE 时,您正在为该会话设置一个环境变量,它会覆盖 build-争论。您不会覆盖整个 docker 构建的构建参数。

如果将 if 语句更改为:

RUN if [ "$BUILD_TYPE" = "Development" ]; then BUILD_TYPE='dev'; fi; echo $BUILD_ENV
RUN if [ "$BUILD_TYPE" = "Production" ]; then BUILD_TYPE='prod'; fi; echo $BUILD_ENV

env var 设置正确,并在行尾回显,但您的最终回显仍将返回构建参数。

如果您改为将这些语句放在一个 shell 脚本中并运行它,它就可以正常工作:

build.sh:

####echo of build build_type does gives me output of Development when passed argument is Development.
if [ "$BUILD_TYPE" = "Development" ]; then BUILD_TYPE='dev'; fi
if [ "$BUILD_TYPE" = "Production" ]; then BUILD_TYPE='prod'; fi
echo "UI BUILD_TYPE=$BUILD_TYPE---------"
##########Calculate the environment type #########

Dockerfile:

###stage 2####################
FROM nginx:alpine

##########Calculate the environment type #########
ARG BUILD_TYPE

COPY build.sh .
RUN ./build.sh

输出:

docker build --build-arg BUILD_TYPE=Production .

Sending build context to Docker daemon  166.9kB
Step 1/4 : FROM nginx:alpine
 ---> 36189e6707f4
Step 2/4 : ARG BUILD_TYPE
 ---> Running in cab2e8749e7e
Removing intermediate container cab2e8749e7e
 ---> ea9ec7779909
Step 3/4 : COPY build.sh .
 ---> 336989bf6389
Step 4/4 : RUN ./build.sh
 ---> Running in ecd09ee58780
UI BUILD_TYPE=prod---------
Removing intermediate container ecd09ee58780
 ---> ed9ca30af483
Successfully built ed9ca30af483

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2019-12-23
    • 1970-01-01
    • 2012-10-26
    • 2013-01-31
    • 1970-01-01
    相关资源
    最近更新 更多