Skip to content

Instantly share code, notes, and snippets.

@thanosa75
Last active March 4, 2022 05:49
Show Gist options
  • Save thanosa75/00b1c14105f4f42495ab to your computer and use it in GitHub Desktop.
Save thanosa75/00b1c14105f4f42495ab to your computer and use it in GitHub Desktop.
Example of SCAN / COUNT looking for patterns in REDIS
#!/bin/bash
# sample code demonstrating a pattern search with SCAN
# using a COUNT "work intent"
if [ $# -ne 3 ]
then
echo "Find matching a pattern using SCAN "
echo "Usage: $0 <host> <port> <pattern>"
exit 1
fi
cursor=-1
keys=""
loops=0
while [ $cursor -ne 0 ]; do
if [ $cursor -eq -1 ]
then
cursor=0
fi
reply=`redis-cli -h $1 -p $2 SCAN $cursor COUNT 10000 MATCH $3`
cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
keys=${reply/$cursor/}
if [[ $keys != "" ]]
then
echo "keys: $keys"
fi
loops=$(( loops + 1 ))
done
echo "loops : $loops"
@wl2776
Copy link

wl2776 commented Apr 20, 2020

This is incorrect solution. If keys, returned in reply, have substrings, equal to cursor, these keys will be corrupted by regex replacement on line 25.
It is better to use arrays:

set -a reply $(redis-cli -h $1 -p $2 SCAN $cursor COUNT 10000 MATCH $3)   # set -A in ksh
cursor=${reply[0]}
keys=${reply[@]:1}

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