3

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.

1
  • The original syntax error is because "$@" in double quotes expands to each positional argument in turn as a separate double-quoted command parameter, whereas "$*" expands to a single double-quoted command parameter. It is not defined what happens when there is other stuff in the double quotes, but it turns out that with positional parameters x and y, "echo '$@'" gives you command parameters "echo 'x" and "y'". So don't do that. (Note that the expansion happens on the local machine, the bash command running in the pod isn't getting any positional parameters). Commented Aug 15, 2024 at 8:53

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that the second -- in the kubectl command is not a Bash option, it serves as the value of $0 when the command given by -c is executed. I usually write dummy in that position to remind myself why there has to be an extra parameter there.
2

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.