Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape $() syntax in `docker exec`

I'm trying to run a command having a $() as an argument (no sure what that's called) that should be evaluated in a Docker container. For example:

docker exec mycontainer echo $(whoami)

When this is executed, whoami is run first, on the host machine, and so the host machine's user gets inserted. Instead, I would like the whoami command to be evaluated in the container such that the container's user is echo'd.

I found it very difficult to find any help on this. Alternatives I've tried that didn't work:

docker exec mycontainer 'echo $(whoami)'
docker exec mycontainer echo '$(whoami)'
docker exec mycontainer echo $$(whoami)
docker exec mycontainer echo \$(whoami)

How can this be achieved?

like image 679
Pieter Jongsma Avatar asked Mar 02 '18 21:03

Pieter Jongsma


1 Answers

You can pass in a single command, with arguments; but that single command can be sh or bash.

docker exec mycontainer sh -c 'echo $(whoami)'

If you need to use Bash syntax in the script fragment (which can really be arbitrarily complex; if you need single quotes inside the quotes, several common workarounds are available) then obviously use bash instead of sh.

like image 55
tripleee Avatar answered Sep 18 '22 18:09

tripleee