Skip to content

Instantly share code, notes, and snippets.

@amyangfei
Last active December 7, 2015 09:23
Show Gist options
  • Save amyangfei/70014944df96df283d7a to your computer and use it in GitHub Desktop.
Save amyangfei/70014944df96df283d7a to your computer and use it in GitHub Desktop.
A simple script to print the size of Redis keys via scan
#!/bin/bash
# This script prints out all of your Redis keys and their size in a human readable format
# Inspired by https://gist.github.com/epicserve/5699837
# Copyright 2015 amyangfei
# License: http://www.apache.org/licenses/LICENSE-2.0
human_size() {
awk -v sum="$1" ' BEGIN {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print sum,"bytes"; } '
}
redis_cmd='redis-cli'
handle_key() {
k=$1
key_size_byte="$($redis_cmd debug object $k | perl -wpe 's/^.+serializedlength:([\d]+).+$/$1/g') $k"
# print out key size info with human readable sizes
size=`echo $key_size_byte | perl -wpe 's/^(\d+).+/$1/g'`; hsize=`human_size "$size"`; key=`echo $key_size_byte | perl -wpe 's/^\d+(.+)/$1/g'`; printf "%-15s%-10s%s\n" "$hsize" "$size" "$k";
}
do_scan() {
saveIFS="$IFS"
IFS=$'\n'
# scan redis keyspace with cursor
arr=()
for k in $($redis_cmd scan $1); do
arr+=("$k")
done
# handle scan result
cursor=${arr[0]}
arr=("${arr[@]:1}")
for key in "${arr[@]}"; do
handle_key $key
done
IFS="$saveIFS"
if [ "$cursor" != "0" ]; then
do_scan $cursor
fi
}
do_scan 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment