check memory and restart service when less than X gb.
bash
#!/bin/bash
# Get the available memory in KB
free_mem_kb=$(free -k | grep Mem | awk '{print $4}')
# Convert to GB (divide by 1024^2)
# without bc
free_mem_gb=$((free_mem_kb / 1024 / 1024))
# with bc
# free_mem_gb=$(echo "scale=2; $free_mem_kb / (1024 * 1024)" | bc)
# Threshold for memory in GB
threshold=2
# Check if free memory is less than the threshold
# without bc
if [ "$free_mem_gb" -lt "$threshold" ]; then
# with bc
# if (( $(echo "$free_mem_gb < $threshold" | bc -l) )); then
echo "Free memory is less than 2GB ($free_mem_gb GB). Restarting Apache..."
# restart some service here
# sudo systemctl restart apache2
else
echo "Free memory is sufficient: $free_mem_gb GB."
fi
No Comments