I want to output the following text in a Dockerfile:
*****first row *****
*****second row *****
One way is to do it like that:
cat > Dockerfile <<EOF
FROM alpine:latest
RUN echo ' *****first row ***** ' >> /home/myfile
RUN echo ' *****second row ***** ' >> /home/myfile
ENTRYPOINT cat /home/myfile; sh;
WORKDIR /home
EOF
But if I have 100 lines it takes time because it runs each command separately and make it as a layer.
Other way is like that:
FROM alpine:latest
RUN printf ' *****first row ***** \n *****second row ***** \n' >> /home/myfile
ENTRYPOINT cat /home/myfile; sh;
WORKDIR /home
but I don't like it because it make it less readable, especially when you have 100 lines.
I wonder is there a way to do something like that:
FROM alpine:latest
RUN echo ' *****first row *****
*****second row ***** ' >> /home/myfile
ENTRYPOINT cat /home/myfile; sh;
WORKDIR /home
Or is there a way to use the ARG
command to do it ?
Use echo With the -e Option to Make Multi-Line String in Bash. The following bash script prints the words to multiline. txt without any extra spaces. The -e option enables the interpretation of escape characters in the variable greet .
There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified with the JSON array format.
Using a backslash is the standard way to break up long lines into multiple lines on Unix-like operating systems. Since most Docker images are built using some form of Linux base image, then the backslash strategy works here as well. Docker also allows for it in other Dockerfile instructions (such as LABEL ).
Each RUN command in a Dockerfile creates a new layer to the Docker image. In general, each layer should try to do one job and the fewer layers in an image the easier it is compress. This is why you see all these '&& 's in the RUN command, so that all the shell commands will take place in a single layer.
There is another question similar to this with a solution: How to write commands with multiple lines in Dockerfile while preserving the new lines?
The answer to this question is more particular in how to use multiline strings in bash rather than how to use Docker.
Following this solution you may accomplish what you want to do as shown below:
RUN echo $' \n\
*****first row ***** \n\
*****second row ***** \n\
*****third row ***** ' >> /home/myfile
More info about this leading dollar sign here: How does the leading dollar sign affect single quotes in Bash?
Note that this syntax relies on the run command using /bin/bash, not /bin/sh.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With