0

I want to extract a pod name from a list of pods available on kubernetes. For example, for the following command

kubectl get pods -n namespace

NAME          READY   STATUS            RESTARTS   AGE
pod1          1/1     Running           2          46d
pod2          1/1     Running           0          46d
test-pod3-yy  0/1     ImagePullBackOff  0          338d
test-pod3-xx  1/1     Running           0          255d

I want to extract pod test-pod3-xx using shell script. Currently this is the command that I'm using

POD_NAME=$(kubectl get pods -n namespace | grep testpod-3 | cut -d' ' -f1)

With this I get both the pods test-pod3-yy and test-pod3-xx but I want to extract the pod that is in running state. How can I do that?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
VIOLET
  • 71
  • 1
  • 9

2 Answers2

5

You can use the field-selector and check for running only:

--field-selector=status.phase=Running

You could also use the -o name flag, to get only the names. With that you'll get:

$ kubectl get pods -n namespace -o name --field-selector=status.phase=Running
pod/pod1
pod/pod2
pod/test-pod3-xx
Chris
  • 5,109
  • 3
  • 19
  • 40
-1
#!/bin/sh -x

kubectl get pods -n namespace > stack

while read line
do
[[ -n $(sed -n '/Running/p' "${line}" ]] && echo "${line}"
done < stack
petrus4
  • 616
  • 4
  • 7
  • 1
    Please paste your script at [shellcheck.net](http://www.shellcheck.net/) and try to implement the recommendations made there. – Cyrus Oct 12 '22 at 08:01