在Dockerfile中迭代RUN命令

时间:2016-09-14 17:02:46

标签: docker sh dockerfile

我有一行看起来像:

RUN for i in `x y z`; do echo "$i"; done

...打算打印三个项目中的每一个

但它引发了/bin/sh: 1: x: not found

知道我做错了吗?

5 个答案:

答案 0 :(得分:12)

看起来你正在使用反引号。反引号中的内容会被执行,反引号中的文本会被结果返回的内容替换。

尝试使用单引号或双引号代替反引号

尝试摆脱这样的反对:

RUN for i in x y z; do echo "$i"; done

答案 1 :(得分:3)

我实际上会建议另一种解决方法。

我们可以退一步,而不是在Docker文件中使用LOOP ......

在独立的bash脚本中实现循环;

这意味着你将拥有一个loop.sh如下:

RUN ./loop.sh

$(document).ready(function(){ var canales = ["umihyu", "smashdota", "vannDota", "ESL_SC2", "freecodecamp"]; var stream = "https://wind-bow.gomix.me/twitch-api/streams/"; var channels = "https://wind-bow.gomix.me/twitch-api/channels/"; for (i=0; i<canales.length; i++){ let logo; let id; let estado; $.getJSON(stream + canales[i] + "/?callback=?", function(data){ if(data.stream==null){ //inicio funcion interna a canales $.getJSON(channels + canales[i] + "/?callback=?", function(data1){ console.log(data1); }); } else { console.log(data); } }); }; });

在您的Dockerfile中,只需执行:

public class Client { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); while (true) { String fileName = sc.nextLine(); System.out.println(fileName); try { File file = new File(fileName); Socket socket = new Socket("localhost", 15000); OutputStream os = socket.getOutputStream(); Writer w = new OutputStreamWriter(os, "UTF-8"); w.write(fileName); w.close(); os.flush(); byte[] mybytearray = new byte[(int) file.length()]; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); bis.read(mybytearray, 0, mybytearray.length); os.write(mybytearray, 0, mybytearray.length); os.flush(); os.close(); socket.close(); } catch (Exception e) { } } } }

以这种方式做这件事的一个好处是:

它只需要一步,这将花费你一层。 您拥有的图层越少,图像尺寸就越小。

https://hackernoon.com/tips-to-reduce-docker-image-sizes-876095da3b34

答案 2 :(得分:0)

对于更易于维护的Dockerfile,我的首选是在RUN指令中使用多行带有注释的注释,尤其是如果将多个操作与&&链接在一起

RUN sh -x \
    #
    # execute a for loop
    #
    && for i in x  \
                y  \
                z; \
       do \
              echo "$i"
       done \
    \
    #
    # and tell builder to have a great day
    #
    && echo "Have a great day!"

答案 3 :(得分:0)

我们可以做到

RUN for i in x \y \z; do echo "$i" "hi"; done
上面命令的

输出将是


x嗨

z hi


写时注意空格-对于x \ y \ z中的i;
示例-git bash的代码段
enter image description here

答案 4 :(得分:-6)

您可以像使用shell命令一样执行循环,而不是使用Run使用CMD

请查看此相关问题以供参考: Recursive while loop in docker cmd

相关问题