Problem
There are a lot of keys in redis, I want to delete some of the keys by pattern from redis-cli, I have modify the default port of the redis and it also require password. The following script can be used to delete the redis keys by pattern.
Script
export REDISCLI_AUTH='redis-password'
REDIS_PORT=<port>
PATTERN="key-pattern.*"
redis-cli -p ${REDIS_PORT} --scan --pattern "${PATTERN}" | xargs -I {} redis-cli -p ${REDIS_PORT} del '{}'
Explanation
- This script export the REDISCLI_AUTH, so we don’t need to specify the password on the redis-cli command line.
- Use the --scan and --pattern options to find keys matching the pattern.
- Pipe the result to xargs with redis-cli to delete the keys.