如何将多个参数传递给shell脚本到`kubectl exec`中?

问题描述

请考虑以下shell脚本,其中POD设置为K8窗格的名称

kubectl exec -it $POD -c messenger -- bash -c "echo '$@'"

当我使用一个参数运行此脚本时,它运行正常。

hq6:bot hqin$ ./Test.sh  x
x

当我用两个参数运行它时,它会炸毁。

hq6:bot hqin$ ./Test.sh  x y
y': -c: line 0: unexpected EOF while looking for matching `''
y': -c: line 1: Syntax error: unexpected end of file

我怀疑参数的传递方式有问题。

如何解决这个问题,以便参数由我的shell逐字扩展,然后作为原义传递给在bash中运行的kubectl exec

请注意,删除单引号只会导致x输出。 另请注意,我需要bash -c,以便最终可以传递文件重定向https://stackoverflow.com/a/49189635/391161

解决方法

我设法通过以下解决方法解决此问题:

kubectl exec -it $POD -c messenger -- bash -c "echo $*"

这似乎还有我可以进行内部重定向的好处。

./Test.sh x y '> /tmp/X'
,

您会想要这样的东西:

kubectl exec POD -c CONTAINER -- sh -c 'echo "$@"' -- "$@"

使用这种语法,我们在容器内运行的命令是echo "$@"。然后,我们获取本地值"$@"并将其作为参数传递给远程Shell,从而在远程Shell中设置$@

在我的本地系统上:

bash-5.0$ ./Test.sh hello
hello
bash-5.0$ ./Test.sh hello world
hello world