How to Use redis-cli: Basic Commands and Usage Guide
Use
redis-cli to connect to your Redis server from the command line by typing redis-cli. Once connected, you can run Redis commands like SET and GET directly to store and retrieve data.Syntax
The basic syntax to start the Redis command line interface is redis-cli [options]. You can connect to a Redis server on a specific host and port using redis-cli -h <host> -p <port>. After connecting, type Redis commands directly to interact with the database.
- redis-cli: Starts the CLI tool.
- -h <host>: Specifies the Redis server hostname (default is localhost).
- -p <port>: Specifies the port number (default is 6379).
- Commands: Redis commands like
SET,GET,DEL, etc.
bash
redis-cli [-h host] [-p port] # Example: Connect to Redis on localhost port 6379 redis-cli # Example: Connect to Redis on remote host 192.168.1.10 port 6380 redis-cli -h 192.168.1.10 -p 6380
Example
This example shows how to start redis-cli, set a key, get its value, and delete the key.
redis
redis-cli 127.0.0.1:6379> SET greeting "Hello, Redis!" OK 127.0.0.1:6379> GET greeting "Hello, Redis!" 127.0.0.1:6379> DEL greeting (integer) 1 127.0.0.1:6379> GET greeting (nil)
Output
OK
"Hello, Redis!"
(integer) 1
(nil)
Common Pitfalls
Common mistakes when using redis-cli include:
- Not specifying the correct host or port if Redis is not on localhost or default port.
- Forgetting to quote strings with spaces in commands like
SET. - Trying to run commands before connecting to the Redis server.
- Confusing Redis command syntax with SQL or other databases.
Always check your connection and command syntax carefully.
redis
redis-cli -h wronghost # Error: Could not connect to Redis server # Wrong command without quotes redis-cli 127.0.0.1:6379> SET message Hello Redis (error) ERR wrong number of arguments for 'set' command # Correct command with quotes 127.0.0.1:6379> SET message "Hello Redis" OK
Output
Could not connect to Redis server
(error) ERR wrong number of arguments for 'set' command
OK
Quick Reference
| Command | Description | Example |
|---|---|---|
| redis-cli | Start Redis CLI connected to localhost:6379 | redis-cli |
| redis-cli -h host -p port | Connect to Redis on specified host and port | redis-cli -h 192.168.1.10 -p 6380 |
| SET key value | Store a string value by key | SET name "Alice" |
| GET key | Retrieve the value of a key | GET name |
| DEL key | Delete a key | DEL name |
| EXIT or QUIT | Exit the redis-cli | QUIT |
Key Takeaways
Start redis-cli by typing 'redis-cli' in your terminal to connect to Redis.
Use '-h' and '-p' options to connect to Redis on a different host or port.
Run Redis commands like SET, GET, and DEL directly inside redis-cli.
Always quote strings with spaces in commands to avoid syntax errors.
Check connection details if redis-cli cannot connect to the server.