Shell Scripts

Shell Scripts by Example

Creating a shell script that sends an Instant Message

Let’s create a script that runs the vmstat command and sends the output to our chatroom. The command vmstat provides us with information about the system over a period of time, which is useful to see that the CPU is not incurring any long-running processes. I am interested in a 10 second period, which is an eternity for a CPU under most circumstances. Here is an example of vmstat on the command line, run one time, taking 5 samples with a 2 second rest between each sample.

vmstat 2 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0  58056  89144  75260 487104    0    0     1     7    4    3  0  0 100  0  0
 0  0  58056  89144  75260 487104    0    0     0     0   23   75  0  0 100  0  0
 0  0  58056  89144  75260 487104    0    0     0     0   28   88  0  0 100  0  0
 0  0  58056  89176  75260 487104    0    0     0     6   25   73  0  0 100  0  0
 0  0  58056  89176  75260 487104    0    0     0    22   40  103  0  0 100  0  0

The output is rather wide for a text message. I am only interested in the last group of data marked “cpu”. If the id column, which represents “idle”, is 100, the CPU is just resting, which is fine. Let’s combine vmstat with sed to isolate the last group of output:

vmstat 2 5|sed 's/.*\(...............\)/\1/'
 ------cpu-----
 us sy id wa st
 0  0 100  0  0
 0  0 100  0  0
 0  0 100  0  0
  0  0 97  4  0
 0  0 100  0  0

Now, I can create my final shell script:

#!/bin/bash
. /etc/profile  # if called from crontab, ensure we have $PATH set
. /root/.profile

TITLE='<ALARMCLOCK> 5 CPU Samples, 2 seconds apart'
VMSTAT=`vmstat 2 5|sed 's/.*\(...............\)/\1/'` # Print the CPU column of vmstat.
                                                      # Take 5 CPU samples, 2 seconds apart.
KK=`printf  "$TITLE\n$VMSTAT"` # Combine Title with results
/usr/local/bin/monitor.chat.sh "$KK"

I save my script to a file called vmstat_sample.sh and chmod it to make it executable. Then I test it, and see the results on my mobile phone:

The message arrives, and it tells me the CPU is idle! No long running process is happening!

Best Practices

Keep in mind these important tips

Memory

Instant Messages About Memory Usage

Storage Space

Get Messages About Storage Space

Last modified November 7, 2020