Flipkart

Tuesday, 7 March 2017

How to Debug a Shell Script-(Linux&UNIX)

In this article, I will explain how to debug a shell script.
I am taking a script which was used in one of my previous articles that generates Alerts whenever /opt File System on your Red Hat/Centos Linux Server exceeds its usage 65%.

Below is the reference:
Shell SCRIPT to Monitor File System Usage/size in Linux

The script used to generate alerts is as shown below:
=====
#!/bin/sh
df -kh | grep "/opt" |  awk '{print $5" "$6}'|cut -d " " -f1 --output-delimiter='  '|tail -n 1 | while read Value;
do
  echo $Value
  fssize=$(echo $Value | awk '{ print $1}' | cut -d'%' -f1)

 if [ $fssize -ge 65 ]; then
mail -s "Alert: /opt is Almost out of disk space on Server `uname -n`, Needs Immediate Attention"
serversupport@domain.com
fi
done
======


 Now, how can a system administrator debug this script to make sure if it works fine before he deploys this script on his production Linux Server?

SCRIPT DEBUGGING:

 1.To start debugging any script, take meaning full lines or parts of a line from the above script which works in a command line and try to get the output for each meaningful Linux command of the script.

Output from my system for the above script is as below:

[root@server2 ~]# df -kh | grep "/opt"
/dev/sda7             7.8G  1.4G  6.1G  68% /opt


 [root@server2 ~]# df -kh | grep "/opt" |  awk '{print $5" "$6}'
68% /opt


[root@server2 ~]# df -kh | grep "/opt" |  awk '{print $5" "$6}'|cut
 -d " " -f1 --output-delimiter='  '
68%


[root@server2 ~]# df -kh | grep "/opt" |  awk '{print $5" "$6}'|cut -d " " -f1 --output-delimiter='  '|tail -n 1
68%

  • Tail command helps us especially if there are more than one lines in the output to select the last line
[root@server2 ~]# echo 18%| awk '{ print $1}' | cut -d'%' -f1
68


Since 68 > 65, script is bound to generate an alert for us.

IMPORTANT NOTE:
  • It is always a better idea to redirect the output of this script to a log file which can be viewed later if you want to track what the script did when this job was actually run.
So a modified Crontab entry would look like below:

CRON ENTRY:

##This job runs every 5 minutes to check file system usage
*/5 * * * * /home/admin/FSalerts.sh > /home/admin/FSalerts.log

 You can open the log file /home/admin/FSalerts.log anytime you wish and see what was the activity done when the job was actually run.

This file is useful to troubleshoot the issues with the script or Cron when you did not receive any alert even if the FS usage exceeded your set threshold.

HAPPY LINUX LEARNING :)

No comments:

Post a Comment