Search code examples
bashshellkuberneteskubectl

A bash command to sum up the numbers in a Kubernetes table?


After using k top pods -A in Kubernetes to get CPU usage and memory, is there any way to sum up those columns with a bash command? Or is it not possible for them to be converted to numbers because of the units? enter image description here I'd like to be able to get the sum of both of these columns, is there a bash command that could do this? I can't seem to figure out how to use awk to do it. I tried awk '{s+=$1}END{print s}', I couldn't really figure it out. The terminal just stopped taking input after that and didn't output anything. Would appreciate help, thanks!


Solution

  • I've never used Kubernetes but some Googling shows that the output really looks like this (which is not what your screen grab showed):

    NAMESPACE            NAME                                                        CPU(cores)   MEMORY(bytes)   
    kube-system          coredns-558bd4d5db-k7mfl                                    8m           11Mi            
    kube-system          coredns-558bd4d5db-qwrrk                                    8m           12Mi            
    

    From the limited research I did it is not clear if the units are always m (milliunits) and Mi (megabyte?). If those are the only unit suffixes then simply ignore them. Since converting a string to a number in Awk ignores any characters after the last digit you don't have to do anything.

    BEGIN {
        cpu = 0
        mem = 0
    }
    NR == 1 { next }
    {
        cpu += $3
        mem += $4
    }
    END {
        print cpu, mem
    }
    

    For the example data above this will print 16 23. If the unit suffix can be other strings you will need to test which suffix is present and apply an appropriate scaling factor to the number.