Passing a command with arguments as a string to docker run
<p>The issue I'm facing is how to pass a command with arguments to <code>docker run</code>. The problem is that <code>docker run</code> does not take command plus arguments as a single string. They need to be provided as individual first-class arguments to <code>docker run</code>, such as:</p>

<pre><code>#!/bin/bash
docker run --rm -it myImage bash -c "(cd build &amp;&amp; make)"
</code></pre>

<p>However consider the command and argument as the value of a variable:</p>

<pre><code>#!/bin/bash -x
DOCKER_COMMAND='bash -c "(cd build &amp;&amp; make)"'
docker run --rm -it myImage "$DOCKER_COMMAND"
</code></pre>

<p>Unfortunately this doesn't work because <code>docker run</code> doesn't understand the substitution:</p>

<pre><code>+ docker run --rm -it myImage 'bash -c "(cd build &amp;&amp; make)"'
docker: Error response from daemon: oci runtime error: exec: "bash -c \"(cd build &amp;&amp; make)\"": stat bash -c "(cd build &amp;&amp; make)": no such file or directory.
</code></pre>

<p>A slight change, removing the quotation of <code>DOCKER_COMMAND</code>:</p>

<pre><code>#!/bin/bash -x
DOCKER_COMMAND='bash -c "(cd build &amp;&amp; make)"'
docker run --rm -it myImage $DOCKER_COMMAND
</code></pre>

<p>Results in:</p>

<pre><code>+ docker run --rm -it myImage 'bash -c "(cd build &amp;&amp; make)"'
build: -c: line 0: unexpected EOF while looking for matching `"'
build: -c: line 1: syntax error: unexpected end of file
</code></pre>

<p>How can I expand a string from a variable so that it is passed as a distinct command and arguments to <code>docker run</code> inside a script?</p>