docker run: how to pass variable values to sh -c

Viewed 24

I am trying to replace the variable value before the sh command

url="google.com"
docker run --rm -it \
--volume="/home/administrator/tmp:/home/simha:rw" \
someimage /bin/sh -c 'ping "${url}"'

FInally I want to do

sh -c 'ping google.com'

So how to substiture the url value in the above.

1 Answers

Since you have the value in single quotes, your host shell won't interpret it; but you're not passing it into the image, so it's not in the container's environment either.

Here I'd suggest removing the sh -c wrapper on the container command, and just running the command you mean.

# set a shell variable in the host shell
url=https://google.com

# launch the container; have the host shell inject that variable
docker run --rm \
  someimage \
  curl "$url"

If you really want a shell inside the container to expand the variable, you need to arrange to pass the variable into the container. One straightforward approach is to use the docker run -e option instead of the host-shell variable

docker run --rm \
  -e url=https://google.com \
  someimage \
  sh -c 'curl "$url"'

Or docker run -e name without a value will copy an environment variable from the host into the container; in a shell context note that the variable must be exported.

url=https://google.com
export url

docker run --rm \
  -e url \
  someimage \
  sh -c 'curl "$url"'
Related