脚本模板
!/bin/bash
NOW_SIZE=
REQUIRE_SIZE=2500
LOG_FILE=/var/log/mem.log
SERVICE_STATUS=0
function check_mem() {
NOW_SIZE=$(free -m | awk '/Mem/{print $4}')
if [[ $NOW_SIZE -le $REQUIRE_SIZE ]]; then
echo "警告:$(date +%F_%H:%m:%S) 内存低于2.5G, 请尽快查看"
else
echo "提示:$(date +%F_%H:%m:%S) 现在内存是 ${NOW_SIZE}M"
fi
}
function run_service() {
while [[ $SERVICE_STATUS -eq 1 ]]; do
{
check_mem
} >>$LOG_FILE
sleep 3
done
exit 0
}
function start_service() {
SERVICE_STATUS=1
run_service
}
function stop_service() {
SERVICE_STATUS=2
}
function main() {
case "$1" in
start)
start_service
;;
stop)
stop_service
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
;;
esac
}
main $1
路径 : /lib/system/systemd/ 定义自己的服务 xxx.service
:'
[Unit]
Description=Check Memory Script
After=network.target
[Service]
Type=simple
ExecStart=/root/scripts/mem.sh start
ExecStop=/root/scripts/mem.sh stop
Restart=on-failure
[Install]
WantedBy=multi-user.target
'