Search code examples
bashshellcut

Code runs fine sometimes and gives Integer expression expected error sometimes


I am writing a code to kill my worker if its memory exceeds a given memory threshold. Below is the code:

#!/bin/bash
memory_usage=`ps -eo size,pid,user,command --sort -size | awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' |cut -d "" -f2 | cut -d "-" -f1 | grep worker | cut -d M -f 1`
echo "Memory usage is ${memory_usage}"
int_memory_usage=${memory_usage%.*}
echo "Int Memory usage is ${int_memory_usage}"
if [ "${int_memory_usage}" -gt 16000 ];
then
    echo "Memory for worker ${memory_usage} above threshold"
    pkill -f "worker"
fi

The code works fine most of the time. It gives the following answer:

Memory usage is       4282.88 
Int Memory usage is       4282

However in some cases it yields the following error:

Memory usage is       4261.01 
         0.34 
Int Memory usage is       4261.01 
         0
/home/kill_worker.sh: line 6: [:       4261.01 
     0: integer expression expected

Please help me find the issue in the code.

Thanks


Solution

  • Thanks for the suggestions. I added the following line in my code and it started working fine.

    memory_usage=`echo "${memory_usage}" | head -1`
    

    Thanks.