How to prevent field splitting when using ENV variables in Docker ENTRYPOINT

By default, variables will be split by space characters. This is not what you want if you have a message that contains spaces for example.

To prevent this, the variable may be surrounded by quotation marks. If you’re using the exec form in the ENTRYPOINT. quotation marks can be escaped with backslashes.

Let's see an example:

entrypoint.sh

Takes two variables (message and version) and prints them.

#!/usr/bin/env sh
set -euo pipefail

# Parameters:
# $1: Message
# $2: Version

printf 'Message is: %s\n' "${1}"
printf 'Version is: %s\n' "${2}"

Dockerfile

# To run:
# docker build . -f Dockerfile -t docker-entrypoint-test && docker run docker-entrypoint-test
FROM alpine

ENV MESSAGE="A message that contains spaces." \
    VERSION=1.4.7

COPY ./entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

# We execute the entrypoint script using the shell to ensure that environment variables are expanded.
# See https://docs.docker.com/engine/reference/builder/#exec-form-entrypoint-example
ENTRYPOINT ["/bin/sh", "-c", "/usr/local/bin/entrypoint.sh \"${MESSAGE}\" ${VERSION}"]

You will see the following output if you build and run it:

If you don’t use spaces around the MESSAGE variable in the ENTRYPOINT. You will see this output:

References: