What it is
redis-cli is the interactive command-line interface for Redis, used for executing commands, inspecting data, and managing your Redis instance.
Installation
Linux (Debian/Ubuntu)
sudo apt update
sudo apt install redis-tools
Linux (Fedora/CentOS/RHEL)
sudo dnf install redis
# or
sudo yum install redis
macOS (using Homebrew)
brew install redis
Windows
Redis is not officially supported on Windows. The recommended approach is to use the Windows Subsystem for Linux (WSL).
- Install WSL: Follow Microsoft’s official guide to install WSL.
- Install Redis within WSL: Once WSL is set up, open your WSL distribution (e.g., Ubuntu) and use the Linux installation commands:
sudo apt update sudo apt install redis-tools
Core Concepts
- Keys: The fundamental identifier for all data in Redis. Keys are strings.
- Data Types: Redis supports several data types, including Strings, Lists, Sets, Sorted Sets, Hashes, Bitmaps, HyperLogLogs, and Streams.
- Database: Redis supports multiple databases (numbered 0-15 by default). You can switch between them.
- Connection:
redis-cliconnects to a Redis server, typically running onlocalhost:6379by default. You can specify host, port, and password.
Commands / Usage
Connecting to Redis
- Connect to default (localhost:6379):
redis-cli - Connect to a specific host and port:
redis-cli -h 192.168.1.100 -p 6380 - Connect with a password:
redis-cli -a your_redis_password - Connect to a specific database:
redis-cli -n 5 - Connect to a Redis Sentinel:
(Theredis-cli -h sentinel.example.com -p 26379 -c-cflag enables cluster mode, useful for connecting to Sentinels or Redis Cluster)
Basic Key Operations
- Set a string value:
SET mykey "Hello Redis" - Get a string value:
GET mykey - Set a key with an expiration time (in seconds):
SET anotherkey "temporary value" EX 60 - Set a key with an expiration time (in milliseconds):
SET yetanotherkey "short lived" PX 500 - Get the remaining time to live (in seconds):
TTL mykey - Check if a key exists:
EXISTS mykey - Delete a key:
DEL mykey - Increment a numeric string:
INCR counter - Decrement a numeric string:
DECR counter - Increment a numeric string by a specific amount:
INCRBY counter 5 - Decrement a numeric string by a specific amount:
DECRBY counter 2
Working with Lists
- Push an element to the left (head) of a list:
LPUSH mylist "item1" - Push an element to the right (tail) of a list:
RPUSH mylist "item2" - Get elements from a list (from index 0 to -1, i.e., all):
LRANGE mylist 0 -1 - Pop an element from the left (head) of a list:
LPOP mylist - Pop an element from the right (tail) of a list:
RPOP mylist - Get the length of a list:
LLEN mylist
Working with Sets
- Add members to a set:
SADD myset "member1" "member2" - Get all members of a set:
SMEMBERS myset - Remove members from a set:
SREM myset "member1" - Check if a member exists in a set:
SISMEMBER myset "member2" - Get the number of members in a set:
SCARD myset
Working with Sorted Sets
- Add members to a sorted set with scores:
ZADD myzset 1 "memberA" 2 "memberB" - Get members of a sorted set, ordered by score (lowest first):
ZRANGE myzset 0 -1 - Get members of a sorted set with their scores:
ZRANGE myzset 0 -1 WITHSCORES - Remove members from a sorted set:
ZREM myzset "memberA" - Get the score of a member:
ZSCORE myzset "memberB" - Get the number of members in a sorted set:
ZCARD myzset
Working with Hashes
- Set a field-value pair within a hash:
HSET user:1000 "name" "Alice" - Set multiple field-value pairs:
HMSET user:1000 "email" "alice@example.com" "age" "30" - Get the value of a field:
HGET user:1000 "name" - Get multiple field values:
HMGET user:1000 "name" "email" - Get all fields in a hash:
HKEYS user:1000 - Get all values in a hash:
HVALS user:1000 - Get all field-value pairs in a hash:
HGETALL user:1000 - Delete a field from a hash:
HDEL user:1000 "age" - Get the number of fields in a hash:
HLEN user:1000
Pub/Sub
- Subscribe to a channel:
(This command will block and wait for messages)SUBSCRIBE channel1 channel2 - Publish a message to a channel:
PUBLISH channel1 "Hello from the client!" - Subscribe to a pattern:
PSUBSCRIBE channel*
Server Management & Information
- Ping the server:
PING - Get server information:
INFO - Get memory usage:
INFO memory - Get clients information:
INFO clients - List all keys (use with caution on large databases):
KEYS * - Scan keys (safer for large databases):
(Provides a cursor and a list of keys; repeat with the new cursor to get more keys)SCAN 0 - Get the time of the Redis server:
TIME - Flush the current database:
FLUSHDB - Flush all databases (use with extreme caution):
FLUSHALL - Save the database to disk (synchronous):
SAVE - Save the database to disk (asynchronous):
BGSAVE - List all running Redis commands:
CLIENT LIST - Kill a client connection:
CLIENT KILL 127.0.0.1:54321 - Monitor all commands being executed:
(This command will block and show all commands; use with caution in production)MONITOR
Transactional Commands
- Start a transaction:
(Subsequent commands are queued)MULTI - Execute the queued commands:
EXEC - Discard the queued commands:
DISCARD - Watch keys for changes before executing a transaction:
(IfWATCH mykeymykeyis modified beforeEXEC, the transaction will fail)
Scripting (Lua)
- Execute a Lua script:
EVAL "return {KEYS[1], ARGV[1]}" 1 mykey myvalue - Execute a Lua script that has been loaded on the server:
EVALSHA 9e9e7c8d7f8e3a1b2c3d4e5f6a7b8c9d0e1f2a3b 2 key1 key2 arg1 arg2 - Load a Lua script into the server’s script cache:
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
redis-cli Specific Flags
--raw: Output in raw format, disabling pretty-printing (useful for scripting).--no-color: Disable colorized output.-h <host>: Specify the Redis server hostname or IP address.-p <port>: Specify the Redis server port.-a <password>: Specify the password for Redis authentication.-n <db>: Specify the database number to connect to.-c: Enable cluster mode (redirects commands if a key is on a different shard).-P <password>: Alias for-a.--eval <file>: Execute Lua script from a file.
Common Patterns
- Set a key and immediately get it:
redis-cli -n 0 SET mykey "some data" && redis-cli -n 0 GET mykey - Check if a key exists, if not, set it:
(Returns 1 if the key was set, 0 otherwise)redis-cli -n 0 SETNX mylock "locked" - Iterate over all keys and delete those matching a pattern:
(Useredis-cli -n 0 KEYS "temp:*" | xargs redis-cli -n 0 DELSCANfor production environments with many keys) - Using
SCANto delete keys:#!/bin/bash CURSOR=0 while true; do read -r CURSOR KEYS_ARRAY < <(redis-cli -n 0 SCAN $CURSOR MATCH "temp:*" COUNT 100) if [ ${#KEYS_ARRAY[@]} -gt 0 ]; then redis-cli -n 0 DEL "${KEYS_ARRAY[@]}" fi if [ "$CURSOR" == "0" ]; then break fi done - Push to a list and trim it to keep only the latest 10 elements:
redis-cli -n 0 "LPUSH mylist 'new_item'" && redis-cli -n 0 "LTRIM mylist 0 9" - Get all members of a set and count them:
(Note:redis-cli -n 0 "SMEMBERS myset" | wc -lSCARDis more efficient for just counting) - Basic health check:
redis-cli PING | grep PONG
Gotchas
KEYS *is blocking: On a production Redis instance with millions of keys, runningKEYS *will block the server and can cause performance issues or timeouts for other clients. Always useSCANin production.MONITORis blocking and verbose: Similar toKEYS,MONITORcan impact performance and generates a lot of output. Use it sparingly for debugging.- Transactions (
MULTI/EXEC) are not atomic in Redis Cluster: While commands within a transaction are executed sequentially, Redis Cluster doesn’t guarantee atomicity across shards if commands involve keys in different slots. FLUSHALLandFLUSHDBare irreversible: These commands delete all data. Double-check your database and environment before executing them.- Default database:
redis-cliconnects to database0by default. If your application uses other databases, remember to specify the correct one with-n <db>. - Authentication: If your Redis server requires a password, you must provide it using
-a <password>orAUTH <password>after connecting. - Cluster Mode (
-c): When connecting to a Redis Cluster, the-cflag is crucial. Without it,redis-cliwon’t be able to redirect commands to the correct nodes if a key happens to be on a different shard. - Scripting
EVALvsEVALSHA:EVALSHAis generally preferred in production because it avoids sending the entire script body over the network each time. You first load the script usingSCRIPT LOADand then reference it by its SHA1 hash. If the script isn’t found on the server (e.g., after a restart),EVALSHAwill fail, and you’ll need to useEVALor reload the script.