File: //ibin/memstats.1
#!/bin/bash
# Create a temporary file to store the stats
temp_file=$(mktemp)
# Use nc with a timeout and strip carriage returns
echo "stats" | nc -w 1 127.0.0.1 11211 | tr -d '\r' > "$temp_file"
# Check that the temp file isn't empty
if [ ! -s "$temp_file" ]; then
echo "Error: no stats received from Memcached."
rm "$temp_file"
exit 1
fi
# Uncomment the next line to debug raw output:
# cat "$temp_file"
# Extract values and remove any stray carriage returns
maxbytes=$(grep "^STAT limit_maxbytes" "$temp_file" | awk '{print $3}' | tr -d '\r')
bytes=$(grep "^STAT bytes " "$temp_file" | awk '{print $3}' | tr -d '\r')
curr_items=$(grep "^STAT curr_items" "$temp_file" | awk '{print $3}' | tr -d '\r')
total_items=$(grep "^STAT total_items" "$temp_file" | awk '{print $3}' | tr -d '\r')
get_hits=$(grep "^STAT get_hits" "$temp_file" | awk '{print $3}' | tr -d '\r')
get_misses=$(grep "^STAT get_misses" "$temp_file" | awk '{print $3}' | tr -d '\r')
# Remove the temporary file
rm "$temp_file"
# Default to 0 if any are empty
maxbytes=${maxbytes:-0}
bytes=${bytes:-0}
curr_items=${curr_items:-0}
total_items=${total_items:-0}
get_hits=${get_hits:-0}
get_misses=${get_misses:-0}
# Calculate hit rate
total=$((get_hits + get_misses))
if [ "$total" -gt 0 ]; then
hitrate=$(echo "scale=2; ($get_hits / $total) * 100" | bc)
else
hitrate="0.00"
fi
# Output results in human-readable format
echo ""
echo "Memcached Stats:"
echo "-----------------------------"
echo "Max Allocated: $(echo "scale=2; $maxbytes / 1024 / 1024" | bc) MB"
echo "Current Usage: $(echo "scale=2; $bytes / 1024 / 1024" | bc) MB"
echo "Current Items: $curr_items"
echo "Total Items Stored: $total_items"
echo "Cache Hits: $get_hits"
echo "Cache Misses: $get_misses"
echo "Hit Rate: $hitrate%"
echo "-----------------------------"
echo ""