怎么用Bash脚本监控Linux上的内存使用情况

2023-04-12 09:33:00 内存 监控 脚本

Bash脚本可以用来监控Linux上的内存使用情况。下面是一个例子:

#!/bin/bash

# monitor memory usage

# set up email address

email="test@example.com"

# set up log file

logfile="/var/log/mem_usage.log"

# set up interval in seconds

interval=60

# set up alert threshold in percent

threshold=90

while true

do

# get current memory usage

usage=$(free -m | awk 'NR==2{printf "%d

", $3*100/$2 }')

# get current date and time

datetime=$(date "+%Y-%m-%d %H:%M:%S")

# log current memory usage and date/time

echo "$datetime, $usage" >> $logfile

# if usage is greater than threshold, send email

if [ "$usage" -gt "$threshold" ]; then

echo -e "Warning! Memory usage is above $threshold%!n" | mail -s "Memory Usage Alert" $email

fi

# wait for specified interval

sleep $interval

done

相关文章