0

I have exported the variables to make sure that even in a new instance of the shell the variable is persisted but it doesn't work... I don't know how I should do it. I've done a lot of research and testing, nothing conclusive.

Dockerfile:

FROM bitnami/minideb:stretch

SHELL ["/bin/bash", "-c"]

ARG VAR1="1"
ARG VAR2="Hello"

# Export arguments
RUN export VAR1="${VAR1}" \
    && export VAR2="${VAR2}"

# Output "Hello world"
RUN if [ $VAR1 = "1" ]; then VAR2+=" world"; fi \
    && echo $VAR2

# Output "Hello" instead of "Hello World"
RUN echo $VAR2

For sure each RUN happens in a new shell.

But why the heck VAR2+=" world" is not persisted since export VAR2="${VAR2} is persisted?

I really don't get it.

Thanks in advance to anyone who finds a way to tackle this odd behaviour.

mtl tech01
  • 45
  • 2
  • 11
  • Possible duplicate of [Dockerfile: Output of RUN instruction into a Variable](https://stackoverflow.com/questions/34213837/dockerfile-output-of-run-instruction-into-a-variable) – Mostafa Hussein Mar 02 '19 at 18:36
  • `RUN export ...` anything is always a no-op; that statement isn't persisted. I think [you're getting the ARG value expanded](https://docs.docker.com/engine/reference/#using-arg-variables) instead. – David Maze Mar 02 '19 at 19:22
  • @DavidMaze No, it's not expanded, those are exported as `env vars` correctly. See my answer, `$VAR1` __is not__ expanded but used only from within `bash` script as I'm using single quotes instead of the double quotes. – Szymon Maszke Mar 03 '19 at 04:05

2 Answers2

1

According to documentation you can either pass environment variable using either of -e, --env, --env-file or bash's export as you did above.

You cannot set the variable using bash script, try to export another variable (say VAR3) inside your if clause.

You can go with something like this answer, but it's really ugly:

FROM bitnami/minideb:stretch

SHELL ["/bin/bash", "-c"]

ARG VAR1="1"
ARG VAR2="Hello"

# Export arguments
RUN export VAR1="${VAR1}" \
    && export VAR2="${VAR2}"

RUN echo 'if [ $VAR1 = "1" ]; then VAR2+=" world"; fi' > ~/.bashrc

# Output "Hello" instead of "Hello World"
RUN source ~/.bashrc && echo "$VAR2"

You could make your script (my_env above) outside of the Docker file and source it from within, or use -e, --env, --env-file, the latter being much better.

Szymon Maszke
  • 22,747
  • 4
  • 43
  • 83
  • I wonder if there's any way to do that in a `.bashrc` it would be cleaner... Since `RUN` make a new instance of the shell everytime. – mtl tech01 Mar 02 '19 at 19:46
  • Just change the filename to `.bashrc`, that's all you would have to do. Not really cleaner in my opinion, but it's your choice. Edited my answer so it works with .bashrc – Szymon Maszke Mar 02 '19 at 20:27
-3

You can try adding "export" :

RUN if [ $VAR1 = "1" ]; then export VAR2+=" world"; fi \
    && echo $VAR2
Machavity
  • 30,841
  • 27
  • 92
  • 100