Dockerfile: output a RUN statement to a variable

I am writing dockerfile and want to put the output of the "ls" command into a variable, as shown below:

$file = ls /tmp/dir 

Here "dir" contains only one file.

The following RUN statement in the docker file does not work

 RUN $file = ls /tmp/dir 
+11
source share
3 answers

You cannot save the variable for later use in other Dockerfile commands (if that is your intention). This is because every RUN happens in a new shell.

However, if you just want to capture the output of the ls you can do this with one compound RUN command. For instance:

 RUN file="$(ls -1 /tmp/dir)" && echo $file 

Or just using subshell inline:

 RUN echo $(ls -1 /tmp/dir) 

Hope this helps you understand. If you have a real mistake or a problem that needs to be solved, I could stop there instead of a hypothetical answer.

A complete Dockerfile example demonstrating this:

 FROM alpine:3.7 RUN mkdir -p /tmp/dir && touch /tmp/dir/file1 /tmp//dir/file2 RUN file="$(ls -1 /tmp/dir)" && echo $file RUN echo $(ls -1 /tmp/dir) 

When building, you should see steps 3 and 4, output a variable (which contains a list of file1 and file2 in step 2):

 $ docker build --no-cache -t test . Sending build context to Docker daemon 2.048kB Step 1/4 : FROM alpine:3.7 ---> 3fd9065eaf02 Step 2/4 : RUN mkdir -p /tmp/dir && touch /tmp/dir/file1 /tmp//dir/file2 ---> Running in abb2fe683e82 Removing intermediate container abb2fe683e82 ---> 2f6dfca9385c Step 3/4 : RUN file="$(ls -1 /tmp/dir)" && echo $file ---> Running in 060a285e3d8a file1 file2 Removing intermediate container 060a285e3d8a ---> 2e4cc2873b8c Step 4/4 : RUN echo $(ls -1 /tmp/dir) ---> Running in 528fc5d6c721 file1 file2 Removing intermediate container 528fc5d6c721 ---> 1be7c54e1f29 Successfully built 1be7c54e1f29 Successfully tagged test:latest 
+16
source

I could not get Andy (or any other) approach to work in the Dockerfile itself, so I set the bash file as the Dockerfile entry point, containing:

 #!/bin/bash file="$(conda list --explicit)" && echo $file echo $(conda list --explicit) 

Please note that the second method does not display line breaks, so I found the first method - echo through the $file variable - improved.

0
source

I used this specifically to print colors on the console. If your container has Python, you can do:

 python -c 'print(" \033[31m RED TEXT \033[0m ")' python -c 'print(" \033[32m GREEN TEXT \033[0m ")' python -c 'print(" \033[34m BLUE TEXT \033[0m ")' 

enter image description here

0
source

Source: https://habr.com/ru/post/1237891/


All Articles