bashshellopenwrtcommand-substitution

How to get Memory Usage for a PID in a variable using bash


This is what I've been working with but haven't been successful,

if [ "$memUsage" -gt "30500" ];
    then
        transUsage=$(pmap 3097 | tail -n 1 | awk '/[0-9]/{print $2}')
        transUsage=$transUsage | awk '/[0-9]/{print $2}' #This was my attempt at removing the extra K
        if [ "$transUsage" -gt "10500" ];
        then
        echo "Terminated this and this"
        fi
    # Print the usage
    echo "Memory Usage: $memUsage KB"
    fi

I need memory usage of PID 3097 in variable so that I could use if command. Currently it outputs,

xxxxK, where x is memory usage size. Due to K being part of size, it's not being being recognized as numeric value.

How to solve this? Would appreciate the help. Regards!


Solution

  • You can use this better code:

    #!/bin/bash
    
    pid=$1
    
    transUsage=$(pmap $pid | awk 'END{sub(/K/, "", $2); print $2}')
    if ((transUsage > 10500)); then
        echo "Terminated this and this"
    fi
    
    echo "Memory Usage: $transUsage KB"
    

    ((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression.