Search code examples
windowsbatch-fileredisredis-cli

Fetch and delete redis data using bat file


I have created a bat file for deleting specific data from Redis DB. I have follwing code

title:Redis Service
@echo off
cls
ECHO "Redis cache clearing started"
ECHO "fetching started method 1"
redis-cli -h 192.134.56.67 -p 6379 -a MyPassword keys "My.Key.*"
ECHO "fetching started method 2"
FOR /F "tokens=* USEBACKQ" %%F IN (`redis-cli -h 192.134.56.67 -p 6379 -a MyPassword keys "My.Key.*"`) DO (
SET var=%%F
)
ECHO "fetching completed"
ECHO %var%
ECHO "deletion started"
FOR /F "tokens=* USEBACKQ" %%F IN (`redis-cli -h 192.134.56.67 -p 6379 -a MyPassword del %var%`) DO (
SET var2=%%F
)
ECHO %var2%
ECHO "deletion completed"
pause

I got Output like this

"Redis cache clearing started"
"fetching started method 2"
 1) "My.Key.2554"
 2) "My.Key.280017"
 3) "My.Key.224"
 4) "My.Key.23730"
 5) "My.Key.2072545"

"fetching completed"
"fetching started method 2"
My.Key.2072545
"deletion started"
1
"deletion completed"

I need to delete whole data from the Redis command output.


Solution

  • Each run of the first loop set's variable var with a new value, so each iteration of the loop will re-assign the new value to var. So by the time you exit that loop, var has only one value which in this case is My.Key.20725545 Instead, use one loop, do not assign variables as you would then need delayedexpansion. So you would need something like this rather. Note!! I do not have redis so I cannot test this result, it is merely an example of how it should probably be:

    @echo off & cls
    title :Redis Service
    echo "Redis cache clearing started"
    for /F "tokens=*" %%f IN ('redis-cli -h 192.134.56.67 -p 6379 -a MyPassword keys "My.Key.*"') do (
     echo "%%~f"
     redis-cli -h 192.134.56.67 -p 6379 -a MyPassword del "%%~f"
    )
    echo deletion completed