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, it does not even include the characters $(.

MeanwhileInHell
  • 6,780
  • 17
  • 57
  • 106
  • Don't use `wc` for this. `if cmd | grep -q ...` works very well to see if `cmd` produces a certain output. – William Pursell Feb 24 '21 at 17:59
  • Error messages should go to stderr, and scripts should return non-zero when they fail: `echo "Some error message" >&2; exit 1` – William Pursell Feb 24 '21 at 18:00
  • 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:05
  • Reviewing this question on the re-open queue... have you tried @thatotherguy's suggestion? If the problem is still there when using `grep "${SERVICE}"`, please post an update. – joanis Feb 26 '21 at 20:46

0 Answers0