Computer Hardware

Shell Script To Get CPU And Memory Utilization

Shell Script has become an indispensable tool for system administrators and developers when it comes to monitoring and managing CPU and memory utilization. With its ability to provide real-time data on these crucial resources, Shell Script helps professionals optimize system performance and ensure efficient resource allocation.

Incorporating a shell script to retrieve CPU and memory utilization is not only efficient but also necessary in today's fast-paced technological landscape. By monitoring these vital resources, professionals can identify bottlenecks, address performance issues, and make informed decisions to improve system efficiency. Whether it's for troubleshooting, capacity planning, or overall system management, a shell script to get CPU and memory utilization is a valuable asset for any IT professional.



Shell Script To Get CPU And Memory Utilization

Introduction to Shell Script to Get CPU and Memory Utilization

The shell script is a powerful tool used in Unix-based operating systems to automate various tasks. One common use case for shell scripting is to collect and monitor system resource utilization, such as CPU and memory usage. By writing a shell script that retrieves this information, system administrators and developers can gain insights into the performance of their systems and make informed decisions to optimize resource allocation.

In this article, we will explore how to create a shell script to get CPU and memory utilization. We will cover different aspects of the script, including retrieving CPU usage metrics, fetching memory usage information, and displaying the results in a user-friendly format. Whether you are a system administrator or a developer, understanding how to monitor these essential resources can be invaluable for maintaining system performance and troubleshooting issues.

Retrieving CPU Usage Metrics

CPU utilization is a vital metric that indicates how much of the CPU's capability is being utilized by running processes. By monitoring CPU usage, system administrators can identify processes that might be causing performance bottlenecks or hogging system resources. Fortunately, there are several commands and tools available in Unix-based systems to retrieve CPU usage metrics.

One commonly used command to check CPU usage is the top command. The top command provides a real-time overview of system resource usage, including CPU utilization. By parsing the output of the top command using command-line tools like awk or grep, we can extract the CPU usage percentage and other relevant information.

Another approach to retrieve CPU usage metrics is through the /proc/stat file. The /proc/stat file contains various system statistics, including CPU usage. By parsing the content of the /proc/stat file using a shell script, we can calculate the CPU usage percentage based on the difference in the CPU time values between subsequent reads. This method allows for a more programmatic and automated approach to retrieve CPU usage metrics.

Once the CPU usage metrics are retrieved using either the top command or parsing the /proc/stat file, the shell script can process and display the information in a user-friendly format. This may include presenting a summary of CPU usage over a specific time interval, identifying processes with high CPU utilization, or generating graphs and reports for further analysis.

Using the Top Command to Retrieve CPU Usage Metrics

The top command is a versatile tool for monitoring system resource usage, including CPU utilization. To retrieve CPU usage metrics using the top command, we can use shell scripting to automate the process.

Here's an example of a shell script that uses the top command to retrieve CPU usage metrics:

#!/bin/bash

# Run the top command and redirect the output to a temporary file
top -b -n 1 > cpu_usage.txt

# Extract the CPU usage percentage from the top command output
cpu_usage=$(awk 'NR==3 {print $2; exit}' cpu_usage.txt)

# Print the CPU usage percentage
echo "Current CPU Usage: $cpu_usage%"

# Clean up the temporary file
rm cpu_usage.txt

In this script, we use the top command with the -b flag to run it in batch mode and the -n 1 flag to retrieve a single snapshot of CPU utilization. The output of the top command is then redirected to a temporary file.

We then use awk to extract the CPU usage percentage from the third line of the output file. This line contains the header "CPU:", followed by the CPU usage percentage. By printing this percentage using echo, we display the current CPU usage to the user.

Finally, we clean up the temporary file using rm to ensure that we are not cluttering the system with unnecessary files. This script provides a basic example of how to use the top command in a shell script to retrieve CPU usage metrics.

Parsing the /proc/stat File to Retrieve CPU Usage Metrics

Another method to retrieve CPU usage metrics is by parsing the /proc/stat file. The /proc/stat file contains various system statistics, including CPU utilization and other performance-related data.

Here's an example shell script that parses the /proc/stat file to calculate and display the CPU usage percentage:

#!/bin/bash

# Function to retrieve CPU statistics from the /proc/stat file
get_cpu_stats() {
    read cpu user nice system idle iowait irq softirq steal guest guest_nice <<< "$(grep 'cpu ' /proc/stat)"
}

# Calculate the total CPU time
get_total_cpu_time() {
    total=$((user + nice + system + idle + iowait + irq + softirq + steal))
}

# Retrieve CPU stats and sleep for 1 second
get_cpu_stats
sleep 1
get_cpu_stats

# Calculate CPU utilization
get_total_cpu_time
prev_total=$total
prev_idle=$idle
idle=$((idle + iowait))
total=$((user + nice + system + idle + iowait + irq + softirq + steal))
diff_total=$((total - prev_total))
diff_idle=$((idle - prev_idle))
cpu_usage=$((100 * (diff_total - diff_idle) / diff_total))

# Print CPU usage percentage
echo "Current CPU Usage: $cpu_usage%"

In this script, we define a function called get_cpu_stats to retrieve the CPU statistics from the /proc/stat file. We then calculate the total CPU time using the get_total_cpu_time function.

We retrieve the CPU stats twice, with a 1-second delay in between, to calculate the difference in CPU time values. By subtracting the previous values from the current values, we can determine the CPU utilization during that time interval.

Finally, we calculate the CPU usage percentage by dividing the difference between the total CPU time and idle time by the total CPU time. This value is then multiplied by 100 to obtain the percentage. The script prints the CPU usage percentage using echo.

Fetching Memory Usage Information

In addition to CPU utilization, monitoring memory usage is crucial for understanding system performance and resource allocation. By regularly monitoring memory usage, system administrators can identify memory-intensive processes, optimize system performance, and avoid potential issues such as memory leaks or insufficient memory for running applications.

Similar to CPU usage, there are various commands and methods available in Unix-based systems to fetch memory usage information using a shell script. Some commonly used commands include free, top, and parsing the /proc/meminfo file.

The free command provides information about the total, used, and free memory on the system. By using the -t option, we can get a summary of total memory usage. By parsing the output of the free command, we can extract the relevant memory usage information and display it in a user-friendly format.

Another approach to fetch memory usage information is by parsing the /proc/meminfo file. The /proc/meminfo file contains information about the system's memory usage, including details about free memory, used memory, and various memory statistics. By extracting and processing the relevant data from the /proc/meminfo file in a shell script, we can obtain detailed memory usage information.

Once the memory usage information is fetched, it can be presented to the user in a human-readable format. This includes displaying the total memory, used memory, free memory, and other memory-related statistics. Additionally, system administrators may choose to set up alerts or notifications based on predefined thresholds to proactively monitor and manage memory usage.

Using the free Command to Fetch Memory Usage Information

The free command is a commonly used tool to fetch memory usage information in Unix-based systems. By incorporating the free command in a shell script, we can automate the process of retrieving memory usage metrics.

Here's an example shell script that uses the free command to fetch memory usage information:

#!/bin/bash

# Run the free command and redirect the output to a temporary file
free -t -h > memory_usage.txt

# Extract the memory usage information from the free command output
total_memory=$(awk 'NR==2 {print $2}' memory_usage.txt)
used_memory=$(awk 'NR==2 {print $3}' memory_usage.txt)
free_memory=$(awk 'NR==2 {print $4}' memory_usage.txt)

# Print the memory usage information
echo "Total Memory: $total_memory"
echo "Used Memory: $used_memory"
echo "Free Memory: $free_memory"

# Clean up the temporary file
rm memory_usage.txt

In this script, we use the free command with the -t option to get a summary of memory usage. The -h flag is used to display the memory sizes in a human-readable format, such as "GB" or "MB". The output of the free command is then redirected to a temporary file.

We use awk to extract the total memory, used memory, and free memory from the second line of the output file. These values are then printed using echo to display the memory usage information to the user. Lastly, we clean up the temporary file using rm.

Parsing the /proc/meminfo File to Fetch Memory Usage Information

Another method to fetch memory usage information is by parsing the /proc/meminfo file. The /proc/meminfo file contains various System V memory statistics and information about the system's memory usage.

Here's an example shell script that parses the /proc/meminfo file to fetch and display memory usage information:

#!/bin/bash

# Function to retrieve memory usage information from the /proc/meminfo file
get_memory_usage() {
    read total_memory <<< "$(grep 'MemTotal' /proc/meminfo)"
    read free_memory <<< "$(grep 'MemFree' /proc/meminfo)"
    read used_memory <<< "$(grep 'MemAvailable' /proc/meminfo)"
}

# Fetch memory usage information
get_memory_usage

# Print memory usage information
echo "Total Memory: $total_memory"
echo "Free Memory: $free_memory"
echo "Used Memory: $used_memory"

In this script, we define a function called get_memory_usage to fetch the memory usage information from the /proc/meminfo file. We use grep to search for specific keywords in the /proc/meminfo file, such as "MemTotal", "MemFree", and "MemAvailable".

By reading the respective lines using read and assigning the values to variables, we can extract the total memory, free memory, and used memory. Finally, we print the memory usage information using echo.

Analyzing CPU and Memory Utilization

Once we have retrieved the CPU and memory utilization metrics, we can analyze and interpret the information to gain insights into system performance and resource usage. This analysis can help identify potential performance bottlenecks, optimize resource allocation, and troubleshoot any issues that may arise.

Some common approaches to analyzing CPU and memory utilization include comparing current usage against historical data, setting up thresholds or alerts for abnormal usage patterns, identifying processes or applications with high resource utilization, and correlating resource usage with system events or user activities.

For CPU utilization, monitoring trends over time can highlight any patterns or spikes in usage that may require attention. It is essential to establish a baseline of CPU usage under normal conditions to identify any significant deviations. By regularly collecting and analyzing CPU utilization data, system administrators can proactively identify potential performance issues and take appropriate actions to mitigate them.

Similarly, for memory utilization, monitoring trends and establishing thresholds can help identify potential memory leaks or applications that consume excessive memory. Analyzing the relationship between memory usage and system events or user activities can also provide valuable insights into resource usage patterns.

Comparing CPU and Memory Utilization with Historical Data

To compare current CPU and memory utilization with historical data, you can store the collected usage metrics in a database or a time series database like InfluxDB or Prometheus. By regularly updating the database with the latest utilization data, historical trends can be visual
Shell Script To Get CPU And Memory Utilization

Shell Script to Get CPU and Memory Utilization

In order to effectively monitor and manage a system, it is crucial to gather information on CPU and Memory utilization. A shell script can be a handy tool to accomplish this task efficiently. The script will provide valuable data that can be analyzed to optimize system performance and identify any bottlenecks.

To get CPU utilization, the script can utilize commands such as "top" or "ps" to retrieve data on processes and their corresponding CPU usage. By monitoring the CPU usage of individual processes, the overall CPU utilization can be obtained.

Similarly, to obtain memory utilization, the script can use commands like "free" or "top" to gather information on the total memory, used memory, and free memory. This data can then be analyzed to ensure efficient memory management.

A well-designed shell script can provide real-time insights into CPU and Memory utilization, which can be further utilized for system optimization and troubleshooting purposes.


### Key Takeaways:
  • Monitoring CPU and memory utilization is essential for system performance optimization.
  • Shell scripting allows you to automate the process of retrieving CPU and memory utilization data.
  • Using the "top" command in a shell script provides real-time CPU and memory utilization information.
  • The "free" command is useful for obtaining memory utilization statistics in a shell script.
  • By scripting CPU and memory utilization monitoring, you can schedule regular checks and receive alerts if thresholds are exceeded.

Frequently Asked Questions

Below are some frequently asked questions about shell scripts for getting CPU and memory utilization:

1. How can I write a shell script to get CPU utilization?

To write a shell script for getting CPU utilization, you can use the "mpstat" command in Linux. Here's an example:

#!/bin/bash
mpstat 1 1 | awk '/Average:/ {print 100 - $NF}'

This script uses the "mpstat" command to get the average CPU utilization over 1 second and then subtracts it from 100 to get the idle CPU percentage.

2. How can I write a shell script to get memory utilization?

To write a shell script for getting memory utilization, you can use the "free" command in Linux. Here's an example:

#!/bin/bash
free | awk 'NR==2{printf "%.2f%%\n", ($3/($3+$4))*100}'

This script uses the "free" command to get the total memory and the used memory. It then calculates the percentage of used memory by dividing the used memory by the total memory and multiplying by 100.

3. Can I combine CPU and memory utilization in a single script?

Yes, you can combine CPU and memory utilization in a single shell script. Here's an example:

#!/bin/bash
cpu_utilization=$(mpstat 1 1 | awk '/Average:/ {print 100 - $NF}')
memory_utilization=$(free | awk 'NR==2{printf "%.2f%%\n", ($3/($3+$4))*100}')

echo "CPU Utilization: $cpu_utilization%"
echo "Memory Utilization: $memory_utilization%"

This script combines the previous CPU and memory utilization scripts. It stores the CPU utilization in the "cpu_utilization" variable and the memory utilization in the "memory_utilization" variable. It then displays both values using the echo command.

4. How can I schedule a shell script to run periodically?

To schedule a shell script to run periodically, you can use the "crontab" command in Linux. Here's how you can do it:

crontab -e

This command opens the crontab file for editing. You can then add an entry to specify when and how frequently you want to run the script. For example, to run the script every hour, you can add the following line:

0 * * * * /path/to/your/script.sh >> /path/to/your/logfile.log 2>&1

This line will run the script located at "/path/to/your/script.sh" every hour. The output of the script will be appended to "/path/to/your/logfile.log".

5. Are there any tools or utilities available to monitor CPU and memory utilization?

Yes, there are several tools and utilities available to monitor CPU and memory utilization. Some popular ones include:

  • top: a command-line utility that provides real-time information about CPU and memory usage.
  • htop: an interactive process viewer that shows CPU and memory usage in a more user-friendly way.
  • glances: a cross-platform monitoring tool that displays CPU, memory, disk, network, and process information.

These tools can be installed on Linux systems and provide more advanced monitoring capabilities compared to simple shell scripts.



In conclusion, using a shell script to obtain CPU and memory utilization provides valuable insights into the performance of a system. By writing a script that utilizes commands like top or ps, we can efficiently monitor and analyze CPU and memory usage.

With the script, we can quickly identify any bottlenecks or potential issues that may be affecting system performance. By regularly monitoring these metrics, we can make informed decisions to optimize resource allocation and ensure the smooth operation of our systems.


Recent Post