Dockerfile:将 RUN 指令输出到变量中 [英] Dockerfile: Output of RUN instruction into a Variable

查看:38
本文介绍了Dockerfile:将 RUN 指令输出到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个dockerfile,想把ls"命令的输出放到一个变量中,如下所示:

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

这里,dir"里面只有一个文件.

Here, "dir" only has one file inside it.

dockerfile 中的以下 RUN 指令不起作用

The following RUN instruction within a dockerfile is not working

RUN $file = ls /tmp/dir

推荐答案

您不能保存变量以供以后在其他 Dockerfile 命令中使用(如果这是您的意图).这是因为每个 RUN 都发生在一个新的 shell 中.

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.

但是,如果您只想捕获 ls 的输出,您应该能够在一个 RUN 复合命令中完成.例如:

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

或者只是使用 subshel​​l 内联:

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.

一个完整的示例 Dockerfile 展示了这一点:

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)

在构建时,您应该看到步骤 3 和 4 输出变量(其中包含在步骤 2 中创建的 file1file2 的列表):

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

这篇关于Dockerfile:将 RUN 指令输出到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆