0

I am running the following command in a bash script:

kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep 'myservice'

but for some reason, it is not returning anything at all. If I run the command in the terminal it returns the expected result, but for some reason, running it in my bash script does not work. Here is my snippet (note, SERVICE is passed in, and verified by echoing it.

echo $(kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep '${SERVICE}')

if [[ $(kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep '${SERVICE}' | wc -l) -eq "0" ]]; then
  echo "ERROR Service [${SERVICE}] does not exist."
  exit
fi

Running this with a valid service name returns:

$ ./script.sh -s myservice

 ERROR Service [myservice] does not exist.

I've tried using backticks, wrapping the $(...) in double-quotes, but it will not execute, so there must be something in the --template section that its not liking. Could someone help me identify what that is please?

EDIT, the linked question does not answer this one, or even include the characters $(. I have tried escaping all single and double quotes in the command, but no use. Actual help would be appreciated.

MeanwhileInHell
  • 6,780
  • 17
  • 57
  • 106
  • Remove the `[[`, `]]`, and the `$(` and `)`. That runs the command and uses the status from `grep` to determine whether the condition is true, leaving the output to appear on standard output. What you've got captures the output and tests whether it is empty or not, without showing you that output. – Jonathan Leffler Feb 24 '21 at 18:01
  • You are trying to use variables in single quoted strings. These do not expand. Compare `SERVICE=foo; echo foobarbaz | grep '${SERVICE}'` vs `SERVICE=foo; echo foobarbaz | grep "${SERVICE}"` – that other guy Feb 24 '21 at 18:04
  • Bingo. Thanks @thatotherguy and JonathanLeffler – MeanwhileInHell Feb 25 '21 at 10:21

0 Answers0