Introduction:
In the realm of system administration, engineering and performance monitoring, keeping a close eye on CPU utilization is paramount. Whether you’re managing a server farm or simply curious about your linux machine’s performance, understanding how to effectively monitor CPU usage is a valuable skill. In this guide, we’ll delve into the intricacies of CPU utilization monitoring and learn how to create a robust shell script to fetch CPU utilization for any given minute.
What is /proc/stat in Linux?
In the Linux environment, /proc/stat
serves as a dynamic system information file that provides real-time statistics about various system resources, including CPU utilization. This pseudo-file aggregates data related to processor usage, such as user-mode, system-mode, and idle time, among others. By parsing /proc/stat
, administrators and monitoring tools gain insights into the performance and workload distribution across CPU cores. Its structured format and accessibility via the procfs virtual file system make it a cornerstone for monitoring and analyzing CPU utilization in Linux-based systems. Understanding /proc/stat
is pivotal for effective system management and performance optimization endeavors.
Understanding ‘sed’ and ‘awk’:
In the Linux ecosystem, sed
and awk
stand as powerful text processing tools, each with its unique set of functionalities.
sed
(Stream Editor):sed
is a versatile command-line utility primarily used for text manipulation in streams or files. It excels at performing tasks such as substitution, deletion, insertion, and more, based on regular expressions. With its concise syntax and robust functionality, sed
is commonly employed for batch editing tasks and text transformations within shell scripts.
awk
:awk
is a versatile programming language designed for text processing and data extraction. Named after its creators – Aho, Weinberger, and Kernighan – awk
operates on a per-line basis, making it ideal for parsing structured data. Its strength lies in its ability to handle fields and records effortlessly, making it a go-to tool for tasks like data manipulation, reporting, and analysis.
Both sed
and awk
are integral components of the Linux command-line toolkit, offering immense flexibility and efficiency in text processing tasks. Mastery of these tools empowers Linux users to tackle a wide array of text processing challenges with elegance and precision.
CPU Utilization Script: Step by Step Procedure
1. Understand the CPU Utilization Computation Formula:
CPU Utilization = [ 1 – ( Total_CPU_Time_Difference / CPU_Idle_Time_Difference ) ] * 100%
The CPU Utilization formula calculates the percentage of time the CPU is actively processing tasks, excluding idle time. It computes this by taking the difference between the total CPU time and the CPU idle time over a specific period, then normalizing it to a percentage scale. In essence, it quantifies the proportion of time the CPU spends performing useful work relative to the total time observed.
2. Filter the CPU Component from /proc/stat
grep ‘cpu ‘ /proc/stat | sed ‘s/cpu //g’ > /root/cpu1
The “> /root/cpu1” part in the syntax indicates that the output will be redirected to a file named cpu1, the second iteration, we will redirect to a file named cpu2
3. Sum all the CPU time values inside /proc/stat
TotalTime1=$(echo $(($(cat /root/cpu1 | sed ‘s/ / + /g’))))
This command will manipulate the /root/cpu1 content using sed command and will add all of its value, and store it on a variable named TotalTime1; same goes for /root/cpu2 in which the other variable will be TotalTime2.
4. Get the CPU Idle Time
IdleTime1=$(cat /root/cpu1 | awk -F ‘ ‘ ‘{print $4}’)
This command will get the 4th value in /root/cpu1 file, which is the actual idle time cpu value, we will store it on a variable named IdleTime1, and IdleTime2 for the second iteration.
5. Get the difference of the two Total CPU time
TotalTimeDiff=$(( ${TotalTime2} – ${TotalTime1} ))
In this, we are just subtracting the two values of CPU total time, that were extracted from a different period of time.
6. Get the difference of the two CPU Idle Time
In this, we are just subtracting the two values of CPU Idle time, that were extracted from a different period of time.
7. Use awk to calculate the actual CPU Percentage
awk -v TotalDiff=”${TotalTimeDiff}” -v IdleDiff=”${IdleTimeDiff}” ‘BEGIN {printf “%.4f\n”, (1 – (IdleDiff / TotalDiff)) * 100}
This line of script is utilizing awk to calculate the actual value of CPU Utilization using the mentioned formula in the initial steps.
8. Set up a shell script with all the necessary stage/step:
9. Test the script.sh
Conclusion
Using this guide, we’ve dwelt into the intricacies of CPU utilization monitoring and learning how to create a robust shell script to fetch CPU utilization for any given minute using awk, sed, variables and content of /proc/stat.
Related Topics:
Linux Articles:
Email Sending in Linux Machine Using Postfix
Tips on How to Pass RedHat Certified Systems Administration Exam
Career Story of a Linux Application Support Engineer: A Journey of Dedication, Resilience, and Excellence
Tips on How to Become a Successful Linux Application Support Engineer
Is Linux in Demand in the Philippines
Unlocking Foundations in Devops: Why Linux is crucial?
Observability Related Topics:
SRE Observability Course
What is Observability?
How to setup a Node Exporter?
Deploy Node Exporter as a Daemon Service
Configure Prometheus Service
1 thought on “Linux Scripting: Create a Shell Script that Checks CPU Utilization”
Comments are closed.