Overview
Redis is an open-source in-memory data store frequently utilized for caching, session management, and pub/sub messaging patterns. This guide explains how to automate Redis operations by embedding commands within bash shell scripts on a Linux system.
Basic Implementation
Connection Setup
Create a new shell script file named redis_exec.sh:
#!/bin/bash
# Redis connection configuration
REDIS_HOST="localhost"
REDIS_PORT="6379"
# Connect to Redis server
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" ping
The script defines connection parameters using variables and attempts to verify connectivity using the Redis PING command.
Performing Database Operations
Extend the script to execute actual data operations:
#!/bin/bash
# Redis connection configuration
REDIS_HOST="localhost"
REDIS_PORT="6379"
# Store a key-value pair
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" SET cache_key "cached_data"
# Retrieve the stored value
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" GET cache_key
This example writes a string value to Redis using the SET command, then retrieves it using GET.
Advanced Script Patterns
Batch Operations
For executing multiple commands sequentially:
#!/bin/bash
REDIS_HOST="localhost"
REDIS_PORT="6379"
CLI="redis-cli -h $REDIS_HOST -p $REDIS_PORT"
# Execute multiple operations
$CLI SET counter "0"
$CLI INCR counter
$CLI INCR counter
$CLI GET counter
This approach stores the redis-cli command in a variable to reduce repetition.
Using HEREDOC for Complex Operations
For executing multiple commands in a single session:
#!/bin/bash
redis-cli -h localhost -p 6379 <<EOF
MSET user:1:name "Alice" user:1:email "alice@example.com"
GET user:1:name
DEL user:1:email
EOF
HEREDOC syntax allows running multiple Redis commands in one invocation, useful for atomic transactions.
Making Scripts Executable
Apply execute permissions to the script:
chmod +x redis_exec.sh
Run the script:
./redis_exec.sh
Common Command Examples
| Operation | Redis Command |
|---|---|
| Set value | SET key value |
| Get value | GET key |
| Delete key | DEL key |
| Check existence | EXISTS key |
| Set expiry | EXPIRE key seconds |
| Increment | INCR key |
| Hash operations | HSET hash field value |
| List operations | LPUSH list value |
Error Handling
Add basic error checking to scripts:
#!/bin/bash
REDIS_HOST="localhost"
REDIS_PORT="6379"
response=$(redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" PING 2>&1)
if [ "$response" = "PONG" ]; then
echo "Redis connection successful"
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" SET test_key "hello"
else
echo "Connection failed: $response"
exit 1
fi
This script verifies conenctivity before performing operations and exits with an error code if Redis is unreachable.
Conclusion
Shell scripts provide a powerful way to automate Redis operations in Linux environments. By combining bash scripting with redis-cli, you can create automated backups, monitoring tasks, and deployment scripts that interact with your Redis datastore.