简体   繁体   中英

Bash Script that gets a count of running processes and then emails if over a certain threshold

I am trying to create a script to grab the current number of running processes and the if that number is over 1000 then send me an email. I am trying to do this in a bash script that I will just use a cron job to call it. The code I am using is below and I am sure I just have something out of place and just need another set of eyes.

PCOUNT=$(cat /proc/loadavg|awk '{print $4}'|awk -F/ '{print $2}')
if [$PCOUNT > 100]; then
    mail -s "Process Count" email@example.com
fi

Your context is incorrect on your if statement. Try (( )) instead of [] on your if like shown below:

PCOUNT=$(cat /proc/loadavg|awk '{print $4}'|awk -F/ '{print $2}')
if (( $PCOUNT > 100 )); then
    mail -s "Process Count" email@example.com
fi

NOTE: I don't have mail setup on my system so I could not verify the mail command.

  • you can cut down awk to

    awk -F" |/" '{print $5}' /proc/loadavg

  • if condition

    [ $PCOUNT -ge 1000

  • mail, pass the $PCOUNT

    mail -s "Process Count: $PCOUNT"

IMHO, if this is for alert why dont you try nagios plugin

After alot of trial and error I finally found a solution. I ended up taking the output of the awk statement and writing it to a file. I then cat the file and send the output to mail.

PCOUNT=$(awk -F" |/" '{print $5}' /proc/loadavg)
if ((PCOUNT>1000)); then
    echo "Number of Running Processes is" $PCOUNT >>/tmp/mail.txt
    cat /tmp/mail.txt | mail -s "Number of processes is rising" example@email.com
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM