Skip to content

Instantly share code, notes, and snippets.

@beisong7
Created January 10, 2025 01:59
Show Gist options
  • Save beisong7/57c4f73482d5294757e2a31f9a1e0bd6 to your computer and use it in GitHub Desktop.
Save beisong7/57c4f73482d5294757e2a31f9a1e0bd6 to your computer and use it in GitHub Desktop.
system maintenance
#!/bin/bash
# Configuration
THRESHOLD_GB=20
ALERT_URL="https://example.com/alert"
# Function to check disk space
check_disk_space() {
free_space=$(df --output=avail -BG / | tail -1 | tr -d 'G')
echo "$free_space"
}
# Function to send alert via curl
send_alert() {
free_space=$1
curl -X POST -H "Content-Type: application/json" \
-d '{"message": "The server is running low on storage. Only '$free_space'GB is free."}' \
"$ALERT_URL"
echo "Alert sent to $ALERT_URL."
}
# Function to delete cache files
delete_cache() {
cache_dirs=("/var/cache" "/tmp")
for directory in "${cache_dirs[@]}"; do
find "$directory" -type f -exec rm -f {} \;
done
echo "Cache files deleted successfully."
}
# Function to delete dangling Docker images
delete_dangling_images() {
if command -v docker &> /dev/null; then
docker image prune -f
echo "Dangling Docker images deleted successfully."
else
echo "Docker is not installed on this system."
fi
}
# Main script
free_space=$(check_disk_space)
echo "Free disk space: ${free_space}GB"
if (( free_space < THRESHOLD_GB )); then
send_alert "$free_space"
delete_cache
delete_dangling_images
else
echo "Sufficient disk space available."
fi
@beisong7
Copy link
Author

#!/bin/bash


get_free_space() {
    df -h --total | awk '/^total/{print $4}' | sed 's/G//'
}

get_treshold() {
    echo 300
}


free_space=$(get_free_space)
threshold_gb=$(get_treshold)
echo "Free disk space: ${free_space}GB"
echo "Threshold space: ${threshold_gb}GB"

# Convert values to integers for comparison
free_space_int=${free_space%.*} # Remove any decimal points
threshold_gb_int=${threshold_gb%.*}


if (( free_space_int < threshold_gb_int )); then
    echo "send alert to admin"

else
    echo "Sufficient disk space available."
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment