Search code examples
dockerdockerfile

Dockerfile - how to echo to a file?


I am trying to create a bash script in dockerfile, but when I try to run it, docker says that the file does not exist. What am I doing wrong?

FROM alpine
USER root
WORKDIR /

RUN mkdir /scripts
RUN echo '#!/bin/bash\necho "test"' >> /scripts/test.sh
RUN chmod +x /scripts/test.sh
ENTRYPOINT ["/scripts/test.sh"]

Solution

  • The apline image has no bash installed, thus the shebang of the script is wrong. Also, the \n in the script will be written to the file literally, not as line break. Therefore, I recommend using printf instead of echo. Furthermore, we should explicitly invoke the sh shell:

    FROM alpine
    USER root
    WORKDIR /
    
    RUN mkdir /scripts
    RUN printf '#!/bin/sh\necho "test"' >> /scripts/test.sh
    RUN chmod +x /scripts/test.sh
    ENTRYPOINT [ "/bin/sh", "/scripts/test.sh" ]