<p>I would like to execute a command in a container (let it be <em>ls</em>) then read the exit code with <em>echo $?</em>
<code>kubectl exec -ti mypod -- bash -c &quot;ls; echo $?&quot;</code> does not work because it returns the exit code of my current shell not the one of the container.</p>
<p>So I tried to use <em>eval</em> on a env varible I defined in my manifest :</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - container2
    image: varunuppal/nonrootsudo
    env:
    - name: resultCmd
      value: 'echo $?'
</code></pre>
<p>then <code>kubectl exec -ti mypod -- bash -c &quot;ls;eval $resultCmd&quot;</code> but the eval command does not return anything.</p>
<pre><code>bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
</code></pre>
<p>Note that I can run these two commands within the container</p>
<pre><code>kubectl exec -ti mypod bash
#ls;eval $resultCmd
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
**0**
</code></pre>
<p>How can I make it work?
Thanks in advance,</p>

<p>This is happening because you use double quotes instead of single ones.
Single quotes won't substitute anything, but double quotes will.</p>
<p>From the bash documentation:</p>
<blockquote>
<p><a href="http://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html" rel="nofollow noreferrer">3.1.2.2 Single
Quotes</a></p>
<p>Enclosing characters in single quotes (<code>'</code>) preserves the literal
value of each character within the quotes. A single quote may not
occur between single quotes, even when preceded by a backslash.</p>
</blockquote>
<p>To summarize, this is how your command should look like:</p>
<pre><code>kubectl exec -ti firstpod -- bash -c 'ls; echo $?'
</code></pre>
