Redis-hkey-backup
lastmod 2024-09-11created 2024-09-113 edits
Backup and restore scripts based on Redis Hash Keys.
redis-cli
Run redis-cli with docker:
#!/usr/bin/env bash
docker run --rm -it \
--network host \
-u "$(id -u):$(id -g)" \
redis:6 \
redis-cli \
"$@"
KEYS script
Check the full list of keys:
#!/usr/bin/env bash
ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)
"${ROOT_DIR}/redis-cli" KEYS '*'
Backup script
The HGETALL command prints output like this:
1) "frame_width"
2) "1920"
3) "frame_height"
4) "1080"
5) "perspective_points"
6) "600,37,479,906,1068,37,1212,906"
7) "mm_x"
8) "5300"
9) "mm_y"
10) "38970"
...
And, though you can't see it, each line ends with a "\r" (CR; Carriage Return) character.
So, to restore with HSET, write the script as follows:
#!/usr/bin/env bash
ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)
if [[ $# -ne 2 ]]; then
echo "Usage: ${BASH_SOURCE[0]} hkey output"
exit 1
fi
"${ROOT_DIR}/redis-cli" HGETALL "$1" | sed \
-e 's/^ *[0-9][0-9]*) *//g' \
-e 's/^"//g' \
-e 's/\r//g' \
-e 's/"$//g' \
> "$2"
-
$1- the Key where the HKEY is stored.
Restore script
#!/usr/bin/env bash
ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)
if [[ $# -ne 2 ]]; then
echo "Usage: ${BASH_SOURCE[0]} input hkey"
exit 1
fi
mapfile -t args < <(cat "$1")
"${ROOT_DIR}/redis-cli" HSET "$2" "${args[@]}"
-
$1- log file path -
$2- the Key to store the HKEY in.