How do I pass multiple arguments to a shell script into `kubectl exec`?

9/23/2020

Consider the following shell script, where POD is set to the name of a K8 pod.

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

When I run this script with one argument, it works fine.

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

When I run it with two arguments, it blows up.

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

I suspect that something is wrong with how the arguments are passed.

How might I fix this so that arguments are expanded literally by my shell and then passed in as literals to the bash running in kubectl exec?

Note that removing the single quotes results in an output of x only. Note also that I need the bash -c so I can eventually pass in file redirection: https://stackoverflow.com/a/49189635/391161.

-- merlin2011
bash
kubectl
kubernetes
positional-parameter

2 Answers

9/23/2020

You're going to want something like this:

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

With this syntax, the command we're running inside the container is echo "$@". We then take the local value of "$@" and pass that as parameters to the remote shell, thus setting $@ in the remote shell.

On my local system:

bash-5.0$ ./Test.sh hello
hello
bash-5.0$ ./Test.sh hello world
hello world
-- larsks
Source: StackOverflow

9/23/2020

I managed to work around this with the following solution:

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

This appears to have the additional benefit that I can do internal redirects.

./Test.sh x y '> /tmp/X'
-- merlin2011
Source: StackOverflow