Dockerfile: Output of RUN instruction into a Variable

后端 未结 3 1700
南旧
南旧 2020-12-09 14:48

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

$file = ls /tmp/dir

Here, \"dir\

3条回答
  •  一向
    一向 (楼主)
    2020-12-09 15:04

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

    However, if you just want to capture the output of ls you should be able to do it in one RUN compound command. For example:

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

    Or just using the subshell inline:

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

    Hope this helps your understanding. If you have an actual error or problem to solve I could expand on this instead of a hypothetical answer.

    A full example Dockerfile demonstrating this would be:

    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 the variable (which contains the list of file1 and file2 creating 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
    

提交回复
热议问题