kubectl exec returns unexcepted error messages?

5/25/2021

I am currently trying to execute a simple bash command onto my kubernetes pod but seem to be getting some errors which does not make sense.

If I exec into the docker container an run the command plain

I have no name!@kafka-0:/tmp$ if [ $(comm -13 <(sort selectedTopics) <(sort topics.sh) | wc -l) -gt 0 ];  then  echo "hello"; fi

I get Hello as output.

But if execute the same from the outside as

kubectl exec --namespace default kafka-0 -c kafka -- bash -c "if [ $(comm -13 </tmp/selectedTopics </tmp/topics.sh| wc -l) -gt 0 ];  then  echo topic does not exist && exit 1; fi"

Then I get an error message stating that /tmp/topics.sh: No such file or directory

event though I able to do this

kubectl exec --namespace $namespace kafka-0 -c kafka -- bash -c "cat /tmp/topics.sh"

why does kubectl exec causing me problems?

-- kafka
bash
kubectl
kubernetes

1 Answer

5/25/2021

When you write:

 kubectl ... "$(cmd)"

cmd is executed on the local host to create the string that is used as the argument to kubectl. In other words, you are executing comm -13 </tmp/selectedTopics </tmp/topics.sh| wc -l on the local host, and not in the pod.

You should use single quotes if you want to avoid expanding locally:

kubectl exec --namespace default kafka-0 -c kafka -- bash -c 'if comm -13 </tmp/topics.sh grep -q . ;  then  echo topic does not exist >&2 && exit 1; fi'
-- William Pursell
Source: StackOverflow