How to output a multiline string in Dockerfile with a single command

If you have a moderately-sized file, it's usually easier to store it in a separate file and just COPY it in.

FROM alpine:latest
COPY myfile.txt /
CMD cat /myfile.txt

This extends to ENTRYPOINT and CMD commands too. Rather than write a complex shell command (especially as an ENTRYPOINT), it's usually easier to write a separate shell script. If it was important for your application to print the contents of that file before running the main thing the container does, you could write an entrypoint script like

#!/bin/sh
cat /myfile.txt
exec "$@"

and then the Dockerfile

FROM alpine:latest
COPY myfile.txt entrypoint.sh /
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["???"]

This also gives you a place to modify the file at runtime (say, using sed(1)) before running the main program if its actual contents need to depend on environment variables or other runtime data.


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.