MST
星途 面试题库

面试题:Bash脚本中如何实现对系统CPU使用率的监控并记录到日志

请编写一个Bash脚本,能够实时获取系统的CPU使用率,并将每5分钟获取到的CPU使用率记录到指定的日志文件中。假设日志文件路径为 /var/log/cpu_usage.log 。
37.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

log_file="/var/log/cpu_usage.log"

while true; do
    cpu_usage=$(top -bn1 | grep '%Cpu' | awk '{print $2}')
    echo "$(date +'%Y-%m-%d %H:%M:%S') CPU使用率: $cpu_usage%" >> $log_file
    sleep 300
done