13

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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Pieter Jongsma
  • 3,365
  • 3
  • 27
  • 30
  • 2
    It's called a command substitution. Doing `echo "$(command)"` is a superbly uselss way to write simply just `command`, and `echo $(command)` is an error unless you specifically require the shell to perform whitespace tokenization and wildcard expansion on the output from the command substitution before passing it to `echo` – tripleee Mar 02 '18 at 21:35
  • 2
    @tripleee Thanks! `echo` is just used as an example here – Pieter Jongsma Mar 02 '18 at 21:56

1 Answers1

19

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Tangentially see also [Difference between `sh` and `bash`](/questions/5725296/difference-between-sh-and-bash) – tripleee Jun 06 '19 at 04:53