Skip to content

Instantly share code, notes, and snippets.

@dk8996
Last active June 10, 2022 21:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dk8996/1f8c92c4c5ea1b4e8997b80e826b90f4 to your computer and use it in GitHub Desktop.
Save dk8996/1f8c92c4c5ea1b4e8997b80e826b90f4 to your computer and use it in GitHub Desktop.
Atomically delete keys matching a pattern in Redis
###################################################################
#Script Name : redis-delete
#Description : Given a host, port and pattern to delete from Redis. Example ./redis-delete.sh redis-XXXX.XXXX.com 6379 stage:*
#Args : <host> <port> <pattern>
#Author : Dimitry Kudryavtsev
#Email : dimitry@mentful.com
###################################################################
if [ $# -ne 3 ]
then
echo "Delete keys from Redis matching a pattern using SCAN & DEL"
echo "Usage: $0 <host> <port> <pattern>"
exit 1
fi
cursor=-1
keys=""
while [ $cursor -ne 0 ]; do
if [ $cursor -eq -1 ]
then
cursor=0
fi
reply=`redis-cli -h $1 -p $2 SCAN $cursor MATCH $3`
cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
if [[ $reply = *[[:space:]]* ]]
then
keys=${reply#[0-9]*[[:space:]]}
for key in $keys; do
echo "Delete the following key: $key"
redis-cli -h $1 -p $2 DEL $key
done
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment