SoFunction
Updated on 2025-04-13

Two steps to set the key expiration time in batches in shell

1. The script is as follows. The function of this script is to find all keys in a database in Redis and set a unified expiration time in batches (it is best left to the development to do this kind of work)

(1) Bulk setting of all keys in db1 through shell script

#!/usr/bin/env bash
#Query all keys under db1 and set the unified expiration time in batches
#Get all keys under db1 and assign values ​​to the variable key through a while loop. -n 1 means entering db1/alidata/redis/bin/redis-cli -h 127.0.0.1 -p 6381  -n 1 keys  '*' |    
while read key
do    
    #Enter db1 and set the unified expiration time to 1296000 seconds in batches    /alidata/redis/bin/redis-cli -h 127.0.0.1 -p 6381  -n 1 expire ${key} 1296000 
done

(2) Log in to redis-6381 to view the effect

[root@jxq-c2-16-2 shell]# sh redis_ttl.sh #Execute script(integer) 1
(integer) 1
(integer) 1

#Login reids6381[root@jxq-c2-16-2 shell]# /alidata/redis/bin/redis-cli -h 127.0.0.1 -p 6381   
127.0.0.1:6381> select 1                  #Enter db1OK
127.0.0.1:6381[1]> keys *
1) "name3"
2) "rocen4"
3) "wenqiang"
127.0.0.1:6381[1]> ttl name3             The expiration time of all keys under #db1 has been changed to 15 days(integer) 1295970
127.0.0.1:6381[1]> ttl rocen4
(integer) 1295963
127.0.0.1:6381[1]> ttl wenqiang
(integer) 1295959

2. The purpose of this script is to find the key in Redis that has not set the expiration time, and set the unified expiration time to 1 hour in batches.

#!/usr/bin/env bash
#Query which keys in db1 have not set expiration time, and set the unified expiration time in batches to 15 days (1296000 seconds)
#Query all keys in db1 and assign values ​​to the variable key through a while loop/alidata/redis/bin/redis-cli -h 127.0.0.1 -p 6381  -n 1 keys  '*' |
while read key
do
    #Get the expiration time of each key in db1    key_val=`/alidata/redis/bin/redis-cli -h 127.0.0.1 -p 6381  -n 1 ttl ${key}`
    #Judge which keys have not set expiration time    if [ "$key_val" -eq "-1" ]
    then
        #Reset the expiration time in db1 with no expiration time set to 3600s        /alidata/redis/bin/redis-cli -h 127.0.0.1 -p 6381  -n 1 expire ${key} 3600
    fi
    
done

This is the article about the methods and steps of setting the key expiration time in shell batch setting. For more relevant shell batch setting the key expiration time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!