Search code examples
bashshellout-of-memoryheap-dump

Need to trigger a script if Memory reaches 80 %


I have a bash script that takes HeapDump. But I need to trigger this automatically when the memory of my machine reaches 80 %.

Can anyone help me with the script? I have my environment running on AWS.

Here is my attempt so far:

#!/bin/bash
threshold=40
threshold2=45
freemem=$(($(free -m |awk 'NR==2 {print $3}') * 100))
usage=$(($freemem / 512))
if [ "$usage" -gt "$threshold" ]

Solution

  • The way the shell works is it examines the exit code of each program to decide what to do next. So you want to refactor your code so it returns 0 (success) when memory is below 80% and some other number otherwise.

    Doing arithmetic in the shell is brittle at best, and impossible if you want floating point rather than integers. You are already using Awk - refactor all the logic into Awk for simplicity and efficiency.

    #!/bin/bash
    # declare a function
    freebelowthres () {
        free -m |
        awk -v thres="$1" 'NR==2 {
            if ($3 * 100 / 512 > thres) exit(1)
            exit(0) }'
    }
    

    Usage: if freebelowthres 80; then...