Skip to content

Instantly share code, notes, and snippets.

@jdp
Created August 21, 2013 19:19
Show Gist options
  • Save jdp/6298952 to your computer and use it in GitHub Desktop.
Save jdp/6298952 to your computer and use it in GitHub Desktop.
Delete keys matching a pattern from Redis
#!/bin/sh
#
# Usage: ./redis-delkeys.sh [-h host] [-p port] [-n db] pattern
#
# Matches keys with the KEYS command matching pattern
# and deletes them from the specified Redis DB.
set -e
HOST="localhost"
PORT="6379"
DB="0"
while getopts "h:p:n:" opt; do
case $opt in
h) HOST=$OPTARG;;
p) PORT=$OPTARG;;
n) DB=$OPTARG;;
\?) echo "invalid option: -$OPTARG" >&2; exit 1;;
esac
done
shift $(( $OPTIND -1 ))
PATTERN="$@"
if [ -z "$PATTERN" ]; then
echo "pattern required" >&2
exit 2
fi
redis-cli -h $HOST -p $PORT -n $DB --raw keys $PATTERN |
xargs redis-cli -h $HOST -p $PORT -n $DB del
@lialun-xm
Copy link

xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option

@jpeyret
Copy link

jpeyret commented Apr 21, 2017

Couldn't get it to work, possibly because I had really complex messy keys (my key is a stringified json object that caches function results by the function parameter contents). So maybe I just fell outside the supported search parameters?

Anyways, for other people looking for this functionality, what did work for me was https://www.npmjs.com/package/redis-utils-cli.

Thanks for all the good work though, no disrespect intended with this link to an alternative.

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