首页 > 解决方案 > kubernetes 在环境中执行命令。带有 eval 的变量

问题描述

我想在容器中执行一个命令(让它成为ls ),然后用echo $? 读取退出代码?kubectl exec -ti mypod -- bash -c "ls; echo $?"不起作用,因为它返回我当前 shell 的退出代码,而不是容器之一。

因此,我尝试在清单中定义的环境变量上使用eval :

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

然后kubectl exec -ti mypod -- bash -c "ls;eval $resultCmd"但 eval 命令不返回任何内容。

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

请注意,我可以在容器中运行这两个命令

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

我怎样才能让它工作?提前致谢,

标签: kubernetesenvironment-variableseval

解决方案


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 $?'

推荐阅读