How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script

1. Script

Today, I will primarily share a shell script that retrieves information about the CPU, memory, and disk I/O of a Linux system.

#!/bin/bash
# Get the local server IP address to monitor
IP=`ifconfig | grep inet | grep -vE 'inet6|127.0.0.1' | awk '{print $2}'`
echo "IP Address:"$IP

# Get total number of CPU cores
cpu_num=`grep -c "model name" /proc/cpuinfo`
echo "Total CPU cores:"$cpu_num

# 1. Get CPU usage
################################################
#us User space CPU percentage
#sy Kernel space CPU percentage
#ni User process space CPU percentage (changed priority)
#id Idle CPU percentage
#wa I/O wait CPU percentage
#hi Hardware interrupts
#si Software interrupts
#################################################
# Get user space CPU percentage
cpu_user=`top -b -n 1 | grep Cpu | awk '{print $2}' | cut -f 1 -d "%"`
echo "User space CPU percentage:"$cpu_user

# Get kernel space CPU percentage
cpu_system=`top -b -n 1 | grep Cpu | awk '{print $4}' | cut -f 1 -d "%"`
echo "Kernel space CPU percentage:"$cpu_system

# Get idle CPU percentage
cpu_idle=`top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f 1 -d "%"`
echo "Idle CPU percentage:"$cpu_idle

# Get I/O wait CPU percentage
cpu_iowait=`top -b -n 1 | grep Cpu | awk '{print $10}' | cut -f 1 -d "%"`
echo "I/O wait CPU percentage:"$cpu_iowait

# 2. Get CPU context switches and interrupt counts
# Get CPU interrupt counts
cpu_interrupt=`vmstat -n 1 1 | sed -n 3p | awk '{print $11}'`
echo "CPU interrupt counts:"$cpu_interrupt

# Get CPU context switch counts
cpu_context_switch=`vmstat -n 1 1 | sed -n 3p | awk '{print $12}'`
echo "CPU context switch counts:"$cpu_context_switch

# 3. Get CPU load information
# Get average load over the last 15 minutes
cpu_load_15min=`uptime | awk '{print $11}' | cut -f 1 -d ','`
echo "CPU load average for the last 15 minutes:"$cpu_load_15min

# Get average load over the last 5 minutes
cpu_load_5min=`uptime | awk '{print $10}' | cut -f 1 -d ','`
echo "CPU load average for the last 5 minutes:"$cpu_load_5min

# Get average load over the last 1 minute
cpu_load_1min=`uptime | awk '{print $9}' | cut -f 1 -d ','`
echo "CPU load average for the last 1 minute:"$cpu_load_1min

# Get task queue length (number of processes waiting to run)
cpu_task_length=`vmstat -n 1 1 | sed -n 3p | awk '{print $1}'`
echo "CPU task queue length:"$cpu_task_length

# 4. Get memory information
# Get total physical memory
mem_total=`free | grep Mem | awk '{print $2}'`
echo "Total physical memory:"$mem_total

# Get total used memory (operating system)
mem_sys_used=`free | grep Mem | awk '{print $3}'`
echo "Total used memory (OS):"$mem_sys_used

# Get total free memory (operating system)
mem_sys_free=`free | grep Mem | awk '{print $4}'`
echo "Total free memory (OS):"$mem_sys_free

# Get total used memory (application)
mem_user_used=`free | sed -n 3p | awk '{print $3}'`
echo "Total used memory (application):"$mem_user_used

# Get total free memory (application)
mem_user_free=`free | sed -n 3p | awk '{print $4}'`
echo "Total free memory (application):"$mem_user_free

# Get total swap size
mem_swap_total=`free | grep Swap | awk '{print $2}'`
echo "Total swap size:"$mem_swap_total

# Get used swap size
mem_swap_used=`free | grep Swap | awk '{print $3}'`
echo "Used swap size:"$mem_swap_used

# Get free swap size
mem_swap_free=`free | grep Swap | awk '{print $4}'`
echo "Free swap size:"$mem_swap_free

# 5. Get disk I/O statistics
# Get statistics for the specified device (/dev/sda)
echo "Statistics for device (/dev/sda)"
# Number of read requests per second
 disk_sda_rs=`iostat -kx | grep sda| awk '{print $4}'`
echo "Read requests per second to the device:"$disk_sda_rs

# Number of write requests per second
disk_sda_ws=`iostat -kx | grep sda| awk '{print $5}'`
echo "Write requests per second to the device:"$disk_sda_ws

# Average I/O request queue length
disk_sda_avgqu_sz=`iostat -kx | grep sda| awk '{print $9}'`
echo "Average I/O request queue length:"$disk_sda_avgqu_sz

# Average time per I/O request
disk_sda_await=`iostat -kx | grep sda| awk '{print $10}'`
echo "Average time per I/O request:"$disk_sda_await

# Average service time for I/O requests
disk_sda_svctm=`iostat -kx | grep sda| awk '{print $11}'`
echo "Average service time for I/O requests:"$disk_sda_svctm

# Percentage of CPU time spent on I/O requests
disk_sda_util=`iostat -kx | grep sda| awk '{print $12}'`
echo "Percentage of CPU time spent on I/O requests:"$disk_sda_util

Execution Result:

How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script

2. Principle Explanation

To understand the reason behind it, we will explain the principles of the script implementation in detail below.

1. Get the local server IP address to monitor

IP=`ifconfig | grep inet | grep -vE 'inet6|127.0.0.1' | awk '{print $2}'`
echo "IP Address:"$IP
  1. ifconfig | grep inet filters out the lines containing the string inet, as shown in the red circle in the image below.
  2. grep -vE ‘inet6|127.0.0.1’ filters out lines containing inet6 and 127.0.0.1 from the first step result.
  3. The second step result is processed by awk to split the string, and $n(0~N) corresponds to the respective parameters, as shown in the image below, where $2 corresponds to Address: 192.168.0.125, **'{print 2}’** prints the value of 2.
  4. The result from the third step is assigned to the variable IP.
  5. echo “IP Address:”$IP prints the value of the variable IP.

2. Get total number of CPU cores

cpu_num=`grep -c "model name" /proc/cpuinfo`
echo "Total CPU cores:"$cpu_num
  1. In Linux, the /proc directory contains many system resource information, where **/proc/cpuinfo** holds important information about the CPU during system operation.
  2. All CPU core information is indicated by the string model name.
  3. By using the command **grep -c "model name" /proc/cpuinfo**, we can count the occurrences of the string model name in the file /proc/cpuinfo. The -c option counts the number of occurrences.

As shown below:

3. Get CPU utilization

The top command is frequently used to monitor the status of Linux systems and is a commonly used performance analysis tool that can display the resource usage of various processes in real-time.

# Get user space CPU percentage
cpu_user=`top -b -n 1 | grep Cpu | awk '{print $2}' | cut -f 1 -d "%"`
echo "User space CPU percentage:"$cpu_user

# Get kernel space CPU percentage
cpu_system=`top -b -n 1 | grep Cpu | awk '{print $4}' | cut -f 1 -d "%"`
echo "Kernel space CPU percentage:"$cpu_system

# Get idle CPU percentage
cpu_idle=`top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f 1 -d "%"`
echo "Idle CPU percentage:"$cpu_idle

# Get I/O wait CPU percentage
cpu_iowait=`top -b -n 1 | grep Cpu | awk '{print $10}' | cut -f 1 -d "%"`
echo "I/O wait CPU percentage:"$cpu_iowait
How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script
top
  1. top -b -n 1 displays system information and prints it in a formatted way, refreshing the results only once.
-n sets the number of times the screen refreshes before exiting.
b formats the top output for file output, allowing you to create process logs.
  1. grep Cpu extracts the line containing the string Cpu.
  2. awk ‘{print $2}’ splits the result from the second step and prints the second string, 0.5%us.
  3. cut -f 1 -d “%” means to split using % as the delimiter, and display the first part of the split result.
-d  "%" is the delimiter.
-f 1 displays the first part of each line split by the delimiter.
  1. Other scripts follow the same logic.

Other CPU utilization parameters are as follows:

#us User space CPU percentage
#sy Kernel space CPU percentage
#ni User process space CPU percentage (changed priority)
#id Idle CPU percentage
#wa I/O wait CPU percentage
#hi Hardware interrupts
#si Software interrupts

4. Get CPU context switches and interrupt counts

# Get CPU interrupt counts
cpu_interrupt=`vmstat -n 1 1 | sed -n 3p | awk '{print $11}'`
echo "CPU interrupt counts:"$cpu_interrupt

# Get CPU context switch counts
cpu_context_switch=`vmstat -n 1 1 | sed -n 3p | awk '{print $12}'`
echo "CPU context switch counts:"$cpu_context_switch

# Get task queue length (number of processes waiting to run)
cpu_task_length=`vmstat -n 1 1 | sed -n 3p | awk '{print $1}'`
echo "CPU task queue length:"$cpu_task_length
  1. vmstat stands for Virtual Memory Statistics, which can monitor the virtual memory, processes, and CPU activity of the operating system. It provides overall statistics of the system but lacks detailed analysis of specific processes.
-n only displays field names once at the beginning.
  1. sed -n 3p prints the third line of the result from the first step.
Options explanation:
    -n or --quiet or --silent cancels automatic printing of the pattern space, only displays the result processed by the script.
Action explanation:
    p: print, which means to print certain selected data. Usually, p runs together with the option sed -n.
  1. **awk ‘{print $1}’`** splits the result from the second step and prints the first string.
How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script
vmstat

5. Get CPU load information

# Get CPU load average for the last 15 minutes
cpu_load_15min=`uptime | awk '{print $11}' | cut -f 1 -d ','`
echo "CPU load average for the last 15 minutes:"$cpu_load_15min

# Get CPU load average for the last 5 minutes
cpu_load_5min=`uptime | awk '{print $10}' | cut -f 1 -d ','`
echo "CPU load average for the last 5 minutes:"$cpu_load_5min

# Get CPU load average for the last 1 minute
cpu_load_1min=`uptime | awk '{print $9}' | cut -f 1 -d ','`
echo "CPU load average for the last 1 minute:"$cpu_load_1min
  1. The uptime command can be used to check how long the server has been running, how many users are currently logged in, and the system’s average load over the past 1 minute, 5 minutes, and 15 minutes. System load is the average number of processes in a runnable or uninterruptible state. A runnable process is either using the CPU or waiting to use the CPU. An uninterruptible process is waiting for some I/O access, such as waiting for disk I/O. The meaning of load averages varies depending on the number of CPUs in the system; a load of 1 on a single CPU system means full load, while on a 4 CPU system it means 75% of the time is idle.
  2. Referring to the previous script analysis, **awk ‘{print $9}’ | cut -f 1 -d ‘,’** splits the result from the first step and gets the 9th string, then splits it by ‘,’ and gets the first string from the split result.
How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script
uptime

6. Get memory information

# Get total physical memory
mem_total=`free | grep Mem | awk '{print $2}'`
echo "Total physical memory:"$mem_total

# Get total used memory (operating system)
mem_sys_used=`free | grep Mem | awk '{print $3}'`
echo "Total used memory (OS):"$mem_sys_used

# Get total free memory (operating system)
mem_sys_free=`free | grep Mem | awk '{print $4}'`
echo "Total free memory (OS):"$mem_sys_free

# Get total used memory (application)
mem_user_used=`free | sed -n 3p | awk '{print $3}'`
echo "Total used memory (application):"$mem_user_used

# Get total free memory (application)
mem_user_free=`free | sed -n 3p | awk '{print $4}'`
echo "Total free memory (application):"$mem_user_free

# Get total swap size
mem_swap_total=`free | grep Swap | awk '{print $2}'`
echo "Total swap size:"$mem_swap_total

# Get used swap size
mem_swap_used=`free | grep Swap | awk '{print $3}'`
echo "Used swap size:"$mem_swap_used

# Get free swap size
mem_swap_free=`free | grep Swap | awk '{print $4}'`
echo "Free swap size:"$mem_swap_free
  1. The free command displays the memory usage of the system, including physical memory, swap memory, and kernel buffer memory.
  2. grep Swap filters the result from the first step to only show lines containing the string Swap.
  3. **awk ‘{print $4}’** splits the result from the second step and prints the value of the fourth string.

How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script【Other scripts refer to previous analysis】

7. Get disk I/O statistics

echo "Statistics for device (/dev/sda)"
# Number of read requests per second
disk_sda_rs=`iostat -kx | grep sda| awk '{print $4}'`
echo "Read requests per second to the device:"$disk_sda_rs

# Number of write requests per second
disk_sda_ws=`iostat -kx | grep sda| awk '{print $5}'`
echo "Write requests per second to the device:"$disk_sda_ws

# Average I/O request queue length
disk_sda_avgqu_sz=`iostat -kx | grep sda| awk '{print $9}'`
echo "Average I/O request queue length:"$disk_sda_avgqu_sz

# Average time per I/O request
disk_sda_await=`iostat -kx | grep sda| awk '{print $10}'`
echo "Average time per I/O request:"$disk_sda_await

# Average service time for I/O requests
disk_sda_svctm=`iostat -kx | grep sda| awk '{print $11}'`
echo "Average service time for I/O requests:"$disk_sda_svctm

# Percentage of CPU time spent on I/O requests
disk_sda_util=`iostat -kx | grep sda| awk '{print $12}'`
echo "Percentage of CPU time spent on I/O requests:"$disk_sda_util
  1. The iostat command is used to monitor the input/output devices and CPU usage of the system. It reports disk activity statistics while also reporting CPU usage.
-k: displays status in kilobytes per second instead of blocks per second
-x: displays extended status
  1. ** grep sda filters the first step result to only show lines containing the string sda.
  2. **awk ‘{print $4}’** splits the result from the second step and only displays the fourth string.
How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script
iostat

iostat is released by Red Hat Enterprise Linux AS and is part of Sysstat. Therefore, we need to install sysstat.

To install the sysstat package:

sudo apt-get install sysstat 

Reference: https://www.toutiao.com/i6754887380399849998/

———— END ————

Recommended Reading

【1】C Language Implementation of MD5 Encryption, So Simple! Must Read
【2】Four Major Objects of the Linux Virtual File System: Superblock, inode, dentry, and file Relationships
【3】[Fan Q&A 11] How to Build a TCP Server in the Intranet and Make it Accessible from the External Network Must Read
【4】Hands-on Guide to Linux Driver 10 – Platform Bus Explained in Detail Must Read
【5】Detailed Explanation of TTY Architecture and UART Driver Based on Linux Must Read
【6】19. Detailed Explanation of Cortex-A9 uboot Startup Code Must Read
【7】Two Divine Beasts Found Must Read
【8】How Many Days Does it Take to Give Up Raising a Dog? Heartless Slap in the Face Must Read
【9】Huawei Genius – Zhi Hui Jun! Must Read
【10】【Spring Festival】 The Story of a Border Collie Escape!
【11】Hello, Li Huan YingMust Read
【12】10,000 Words and 30 Images to Explain the TCP ProtocolMust Read

How to Get Linux Memory, CPU, Disk I/O Information with a Shell Script

To join the group, please add a personal WeChat account, and I will guide you through embedded entry and advancement.

Reply “1024” in the public account to get free learning materials, looking forward to your attention~

Leave a Comment