Maximilian
Maximilian

Reputation: 8510

Iterate in RUN command in Dockerfile

I have a line that looks something like:

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

...with the intention of printing each of the three items

But it raises /bin/sh: 1: x: not found

Any idea what I'm doing wrong?

Upvotes: 27

Views: 62192

Answers (5)

Tom Tang
Tom Tang

Reputation: 1144

I would suggest an alternative solution of this.

In stead of having the LOOP inside docker file, can we take a step back ...

Implement the loop inside a independent bash script;

Which means you would have a loop.sh as following:

#!/bin/bash

for i in $(seq 1 5); do echo "$i"; done

And in your Dockerfile, you will need to do:

COPY loop.sh loop.sh
RUN ./loop.sh

With the approach aboved it requires one extra step and costs one extra layer.

However, when you are going to do some more complicated stuff, I would recommend to put them all into the script.

All the operations inside the script will only cost one layer.

To me this approach is could be cleaner and more maintainable.

Please also have a read at this one: https://hackernoon.com/tips-to-reduce-docker-image-sizes-876095da3b34

Upvotes: 15

ChaitanyaBhatt
ChaitanyaBhatt

Reputation: 1226

Run Docker container perpetually by writing a simple script

docker run -d <container id> \
sh -c "while :; do echo 'just looping here... nothing special'; sleep 1; done"

Upvotes: 2

Anurag_BEHS
Anurag_BEHS

Reputation: 1480

We can do it like

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

output of above command will be


x hi
y hi
z hi


Mind spaces while writing - for i in x \y \z;
example - snippet from git bash
enter image description here

Upvotes: 3

brianNotBob
brianNotBob

Reputation: 586

For a more maintainable Dockerfile, my preference is to use multiple lines with comments in RUN instructions especially if chaining multiple operations with &&

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!"

Upvotes: 10

arjabbar
arjabbar

Reputation: 6404

It looks like you're using backticks. What's in backticks gets executed and the text in the backticks gets replaced by what's returned by the results.

Try using single quotes or double quotes instead of backticks.

Try getting rid of the backticks like so:

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

Upvotes: 39

Related Questions