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:

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


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

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

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

# We execute the entrypoint script using the shell to ensure that environment variables are expanded.
# See
ENTRYPOINT ["/bin/sh", "-c", "/usr/local/bin/ \"${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: