Requirements: accurately monitor CPU with top command
Preparation knowledge: Top use, basic awk, DC (default bash shell does not support decimal operations)
The script is as follows
[[email protected] scripts]# cat cpu.sh #!/bin/bash -# top -n 参数指定运行次数,1代表运行一次即停止,不再等待top数据更新,使用awk指定分割符,提取数据cpu_us=`top -n 1 | grep ‘Cpu(s)‘ | awk -F‘[" "%]+‘ ‘{print $2}‘`cpu_sy=`top -n 1 | grep ‘Cpu(s)‘ | awk -F‘[" "%]+‘ ‘{print $4}‘`cpu_idle=`top -n 1 | grep ‘Cpu(s)‘ | awk -F‘[" "%]+‘ ‘{print $8}‘`# 默认bash shell不能直接运算小数点,所以需要借助bc# bc命令是一种支持任意精度的交互执行的计算器语言。# 常见用法 echo "1.23*5" | bc cpu_sum=$(echo "$cpu_us+$cpu_sy"|bc)echo "CPU_SUM: $cpu_sum%"echo "CPU_Idle: ${cpu_idle}%"#超过阀值即发送邮件if [ $cpu_sum -ge 90 ];then
Result of Operation
The script can be added to the scheduled task
This concludes.
Shell script case (iii) accurately monitor CPU usage with the top command