Use shell script to query the utilization rate of CPU, memory and disk partition of the server



This article will write a shell script to queryUtilization rate of CPU, memory and disk partition of Linux serverShell script is actually composed of basic shell commands, so when writing shell scripts, you need to know the commonly used commands. If you are not very clear, you can refer to this article: Linux learning 1: common basic linux commands.


#Calculate CPU utilization, - N number: Specifies the maximum number of iterations or frames that should be generated before the end. Generally, the larger the number of iterations, the more accurate the CPU utilization rate can be obtained; in this script, there are five iterations, "- N5" 
cpu=`top -b -n5 | fgrep "Cpu(s)" | tail -1 | awk -F'id,' '{split($1, vs, ","); v=vs[length(vs)]; sub(/\s+/, "", v);sub(/\s+/, "", v); printf "%d", 100-v;}'`
echo $cpu'%'
#Statistics of memory usage
mem_used_persent=`free -m | awk -F '[ :]+' 'NR==2{printf "%d", ($3)/$2*100}'`
#The - e parameter is used to make the "\ n" newline character take effect to wrap the output line
echo -e $mem_used_persent'%\n'
#Statistics of partition usage, DF - P parameter can prevent the printout content from wrapping
df -THP | awk -F '[ ]+' 'NR!=1{print $1","$6}'


After the script is written, it will wait for the following output results:



The first two lines read:12%: CPU utilization rate; 37%: memory utilization rate;

The next four lines: the usage rate of each partition, the partition name and its usage rateEnglish commaseparate.


You can use the command before the script is written and runbash -n .shDetermine whether there is a syntax error in the script. If there is a syntax error, use the command againbash -x .shRun the script step by step to see where there is a syntax error.

Mei Don’t forget to leave the footprints of your study

If you don’t like the article, you are “playing rogue”. Haha (◍◍◍◍◍◍) ゙! A joke, move your little hand, praise is finished, you each give a strength (like + comment) will let more learners join in! Thank you very much.  ̄ω ̄=