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

查看:486
本文介绍了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.

docker文件中的以下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 表明这将是:

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中创建的 file1 file2 的列表) :

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天全站免登陆