Skip to content

Instantly share code, notes, and snippets.

@samsav
Created October 2, 2025 18:39
Show Gist options
  • Select an option

  • Save samsav/9512ff5065399a6f1735b73a48c7b932 to your computer and use it in GitHub Desktop.

Select an option

Save samsav/9512ff5065399a6f1735b73a48c7b932 to your computer and use it in GitHub Desktop.
A bash script and systemd files for periodically logging memory use on a host
[Unit]
Description=Log memory usage and top processes on an EC2 instance running Amazon Linux 2023
[Service]
Type=oneshot
ExecStartPre=/usr/bin/mkdir -p /home/ec2-user/memlog
ExecStart=/home/ec2-user/log_memory_usage.sh /home/ec2-user/memlog/memory_summary.log /home/ec2-user/memlog/top_processes.log
StandardOutput=journal
StandardError=journal
User=ec2-user
[Unit]
Description=Run memory usage logger every minute during working hours
[Timer]
OnCalendar=Mon..Fri *-*-* 08:00..18:00:00
Persistent=true
[Install]
WantedBy=timers.target
#!/bin/bash
if [ -z "$2" ]; then
echo "Usage: $0 <memory_summary_log_file> <top_processes_log_file>"
exit 1
fi
MEM_SUMMARY_FILE="$1"
TOP_PROCESSES_FILE="$2"
CURRENT_TIMESTAMP=$(date)
# Get total and used memory in MiB and calculate percentage
# Use awk to pick up the second line of free -m output and format it
MEM_INFO=$(free -m | awk 'NR==2{printf "%sMiB %.2f%%", $3, $3/$2*100}')
# Output to memory summary file
echo "$CURRENT_TIMESTAMP Total Used Memory: $MEM_INFO" >>"$MEM_SUMMARY_FILE"
# Output to top processes file
echo "$CURRENT_TIMESTAMP" >>"$TOP_PROCESSES_FILE"
# Use if-else in awk to print header for the first line
ps aux --sort -rss | head -n 11 | awk '{if(NR==1) print $1, $11, "%MEM"; else print $1, $11, $4}' >>"$TOP_PROCESSES_FILE"
logger "Memory summary logged to $MEM_SUMMARY_FILE"
logger "Top processes logged to $TOP_PROCESSES_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment