Reputation: 43
This prints blank:
docker run --rm --env HELLO="world" ubuntu:18.04 bash -c "echo $HELLO"
However this works:
docker run --rm -it --env HELLO="world" ubuntu:18.04 bash
# in the container
echo $HELLO
HELLO
seems passed to the container though:
docker run --rm --env HELLO="world" ubuntu:18.04 env
Why is the first command not seeing HELLO
? What am I missing?
Upvotes: 3
Views: 4054
Reputation: 11980
Because of the double quotes, $HELLO
will be evaluated by the docker host itself once the command got executed before going inside the container. So you need to either escape the dollar sign ($
) using Backslash (\
) which tells the bash that the $
is a part of the command itself and no need to be evaluated by the current shell (which is the docker host in our case) or use single quotes (''
) like this:
Using single quotes
$ docker run --rm --env HELLO="world" ubuntu:18.04 bash -c 'echo $HELLO'
world
Using Backslash to escape
$ docker run --rm --env HELLO="world" ubuntu:18.04 bash -c "echo \$HELLO"
world
Upvotes: 7
Reputation: 15223
The reason you are not seeing what you expect is because things are being evaluated before you expect them to be evaluated.
When you run:
docker run --rm --env HELLO="world" ubuntu:18.04 bash -c "echo $HELLO"
The "echo $HELLO"
really isn't any different to bash than:
echo "echo $HELLO"
The shell (bash
) parses double quotes ("
) and things inside them. It sees "echo $HELLO"
and replaces the variable $HOME
with it's value. If $HOME
is not defined, this evaluates to echo
.
So,
echo "echo $HELLO"
is parsed and evaluted by your shell. Which then just runs this at the end:
echo "echo "
So the "echo $HELLO"
in your docker command is evaluated to "echo "
and that's what gets passed to the docker command.
What you want to do is to prevent your shell from evaluating the variable. You can do it a couple of ways:
You can use single quotes instead of double quotes. Your shell doesn't parse it; it will be passed to the bash
inside the container as is:
docker run --rm --env HELLO="world" ubuntu:18.04 bash -c 'echo $HELLO'
You can escape the $
to avoid evaluating it in this shell and let the bash
inside the docker container evaluate it:
docker run --rm --env HELLO="world" ubuntu:18.04 bash -c "echo \$HELLO"
Upvotes: 0