joesan
joesan

Reputation: 15355

Dockerfile capture output of a command

I have the following line in my Dockerfile which is supposed to capture the display number of the host:

RUN      DISPLAY_NUMBER="$(echo $DISPLAY | cut -d. -f1 | cut -d: -f2)" && echo $DISPLAY_NUMBER

When I tried to build the Dockerfile, the DISPLAY_NUMBER is empty. But however when I run the same command directly in the terminal I get the see the result. Is there anything that I'm doing wrong here?

Upvotes: 2

Views: 2328

Answers (2)

Uku Loskit
Uku Loskit

Reputation: 42040

Host environment variables cannot be passed during build, only at run-time.

Only build args can be specified by:

first "declaring the arg"

ARG DISPLAY_NUMBER

and then running docker build . --no-cache -t disp --build-arg DISPLAY_NUMBER=$DISPLAY_NUMBER

You can work around this issue using the envsubst trick

RUN      echo $DISPLAY_NUMBER

And on the command line:

envsubst < Dockerfile | docker build . -f -

Which will rewrite the Dockerfile in memory and pass it to Docker with the environment variable changed.

Edit: Note that this solution is pretty useless though, because you probably want to do this during run-time anyways, because this value should depend on not on where the image is built, but rather where it is run.

I would personally move that logic into your ENTRYPOINT or CMD script.

Upvotes: 1

mbuechmann
mbuechmann

Reputation: 5740

Commands specified with RUN are executed when the image is built. There is no display during build hence the output is empty.

You can exchange RUN with ENTRYPOINT then the command is executed when the docker starts.

But how to forward the hosts display to the container is another matter entirely.

Upvotes: 2

Related Questions