<p>I want a shell scripts for find which kubernetes pods is newly added to the cluster. Include the pod name,date&amp;Time and Namespace.</p>

<p>I have tried with the following bash script:</p>

<pre><code>#!/bin/bash

p=50            #total pods count

pcount=`kubectl get pods |wc -l`

###Addition check
if [ $ncount -gt $n ]
then

    ####pods variable have all pods name.
    pods=`kubectl get pods|awk '{print $1}'|awk '{if(NR&gt;1)print}'| xargs`

    ###start variable have all dates pods created

    start=`kubectl describe pod $pods |grep "Start Time"|awk '{print $3 $4 $5 $6}'`

    ###max variable have total number of pods
    max=`kubectl get pods |awk '{if(NR&gt;1)print}'| wc -l`

    dt=`date +%a,%d%b%Y`

    array=( $start )

    i=0
    while [  $i -lt $max ];
    do
        #    echo "inside loop ${array[$i]}"

        if [[ "$dt" == "${array[$i]}" ]];then
             dat=`date "+%a, %d %b %Y"`
             name=`kubectl describe pod $pods |grep -v SecretName: |echo "$dat" |egrep 'Name|Start Time'`

             printf "\n"
             echo "Newly Added pods are: $name"
        fi
        i=$(( $i + 1 ))
    done
fi
</code></pre>

<p>The script working almost fine. But I need only today's created pods,the scripts showing all pods Name, Start Time and Namespace.</p>

<p>Please help.</p>

Steven Lung
<p>Your script has numerous issues and inefficiencies.  Repeatedly calling a somewhat heavy command like <code>kubectl</code> should be avoided; try to rearrange things so that you only run it once, and extract the information you need from it.  I'm vaguely guessing you actually want something along the lines of</p>

<pre><code>#!/bin/bash

# Store pod names in an array  
pods=($(kubectl get pods |
    awk 'NR&gt;1 { printf sep $1; sep=" "}'))
if [ ${#pods[@]} -gt $n ]; then  # $n is still undefined!
    for pod in "${pods[@]}"; do
        kubectl describe pod "$pod" |
        awk -v dt="$(date +"%a, %d %b %Y")" '
            /SecretName:/ { next }
            /Name:/ { name=$NF }
            /Start Time:/ { t=$3 $4 $5 $6;
                if (t==dt) print name
                name="" }'
    done
fi
</code></pre>

<p>Once you run Awk anyway, it makes sense to refactor as much as the processing into Awk; it can do everything <code>grep</code> and <code>cut</code> and <code>sed</code> can do, and much more.  Notice also how we use the <code>$(command)</code> command substitution syntax in preference over the obsolescent legacy <code>`command`</code> syntax.</p>

<p><code>kubectl</code> with <code>-o=json</code> would probably be a lot easier and more straightforward to process programmatically so you should really look into that. I don't have a Kubernetes cluster to play around with so I'm only pointing this out as a direction for further improvement.</p>
