以下是一个 shell脚本,可以在服务器上每隔1分钟输出一句话,告诉当前的 CPU 和内存利用率:
#!/bin/bash
while true; do
cpu_usage=$(top -b -n 1 | grep "Cpu(s)" | awk '{print $2 + $4}')
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100}')
echo "CPU使用率: $cpu_usage%"
echo "内存使用率: $mem_usage%"
sleep 60
done
脚本使用了一个无限循环,每隔60秒输出一次 CPU 和内存利用率。具体来说,top -b -n 1 | grep "Cpu(s)" | awk '{print $2 + $4}'
命令用于获取当前 CPU 的使用率,free | grep Mem | awk '{print $3/$2 * 100}'
命令用于获取当前内存的使用率。sleep 60
命令用于让脚本暂停60秒。
将该脚本保存为 cpu_mem_usage.sh
文件,并给予执行权限(chmod +x cpu_mem_usage.sh
),即可在服务器上运行该脚本。运行脚本时,可以使用 ./cpu_mem_usage.sh
命令启动脚本,按下 Ctrl + C
键可以停止脚本的执行。