Abdelghani
Abdelghani

Reputation: 745

kubernetes execute a command in a env. varible with eval

I would like to execute a command in a container (let it be ls) then read the exit code with echo $? kubectl exec -ti mypod -- bash -c "ls; echo $?" does not work because it returns the exit code of my current shell not the one of the container.

So I tried to use eval on a env varible I defined in my manifest :

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - container2
    image: varunuppal/nonrootsudo
    env:
    - name: resultCmd
      value: 'echo $?'

then kubectl exec -ti mypod -- bash -c "ls;eval $resultCmd" but the eval command does not return anything.

bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr

Note that I can run these two commands within the container

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**

How can I make it work? Thanks in advance,

Upvotes: 1

Views: 2041

Answers (3)

Abdelghani
Abdelghani

Reputation: 745

Thanks Kurtis Rader and Thomas for your answers.

It also works when I precede the $? with a backslash :

kubectl exec -ti firstpod -- bash -c "ls; echo \$?"

Upvotes: 0

acid_fuji
acid_fuji

Reputation: 6853

This is happening because you use double quotes instead of single ones. Single quotes won't substitute anything, but double quotes will.

From the bash documentation:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') 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.

To summarize, this is how your command should look like:

kubectl exec -ti firstpod -- bash -c 'ls; echo $?'

Upvotes: 1

Kurtis Rader
Kurtis Rader

Reputation: 7469

Using the POSIX shell eval command is wrong 99.999% of the time. Even if you ignore the presence of Kubernetes in this question. The problem in your question is that your kubectl command is expanding the definition of $resultCmd in the shell you ran the kubectl command. Specifically due to your use of double-quotes. That interactive shell has no knowledge of the definition of $resultCmd in your "manifest" file. So that shell replaces $resultCmd with nothing.

Upvotes: 0

Related Questions