面试题答案
一键面试以下是实现该功能的Bash脚本:
#!/bin/bash
# 读取配置文件
config_file="config.txt"
if [ -f "$config_file" ]; then
source "$config_file"
else
echo "配置文件 $config_file 不存在,使用默认阈值"
threshold_high=70
threshold_low=30
fi
# 获取磁盘空间使用率
usage=$(df -h | awk '$NF=="/"{print $(NF-1)}' | sed 's/%//')
# 判断磁盘空间使用率并发送邮件
if (( $(echo "$usage > $threshold_high" | bc -l) )); then
echo "磁盘空间使用率超过 $threshold_high%,当前使用率为 $usage%" | mail -s "磁盘空间警告" your_email@example.com
elif (( $(echo "$usage < $threshold_low" | bc -l) )); then
echo "磁盘空间使用率低于 $threshold_low%,当前使用率为 $usage%" | mail -s "磁盘空间恢复正常" your_email@example.com
fi
假设配置文件config.txt
内容示例如下:
threshold_high=80
threshold_low=20
请将your_email@example.com
替换为实际接收邮件的邮箱地址。同时确保服务器已配置好邮件发送功能(例如安装并配置mailutils
等邮件客户端)。