Host vs. Container Environment Variables in docker exec command

Munish Goyal
An Idea (by Ingenious Piece)
1 min readJul 19, 2020

The first case passes the host’s environment variable as part of the command, whereas the second case uses the container’s environment variable are used.

<span>Photo by <a href=”https://unsplash.com/@frankiefoto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditC
Photo by frank mckenna on Unsplash

Take a look at the below example, on how to use environment variable from host machine vs. container while running docker exec:

# pull the image
docker pull goyalmunish/devenv
# fetching env. variable from host machine
docker exec -it devenv /bin/bash -c "echo $HOME" # /home/ubuntu
# fetching env. variable from container
# use single quotes to escape parsing of environment variable from host machine itself
docker exec -it devenv /bin/bash -c 'echo $HOME' # /root

As we can see, the first case passes the host’s environment variable as part of the command, whereas the second case uses the container’s environment variable are used.

..and this is obvious if you recall the difference between bash’s single quotes (full-quoting) and double quotes (partial-quoting).

Here are some related interesting stories that you might find helpful:

--

--

Munish Goyal
An Idea (by Ingenious Piece)

Designing and building large-scale data-intensive cloud-based applications/APIs.