Last active
December 26, 2024 17:50
-
-
Save davidliyutong/a849e6f6a3bf7aaa66dffd0f78c1b333 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 检查参数个数 | |
if [ "$#" -lt 3 ]; then | |
echo "Usage:" | |
echo "./tool backup <volume> <output-file>" | |
echo "./tool restore <input-file> <volume>" | |
exit 1 | |
fi | |
COMMAND=$1 | |
# 检查 Docker 是否安装 | |
if ! command -v docker &> /dev/null; then | |
echo "Docker is not installed. Please install Docker first." | |
exit 1 | |
fi | |
case $COMMAND in | |
backup) | |
VOLUME=$2 | |
FILE=$3 | |
# 检查 Volume 是否存在 | |
if ! docker volume inspect "$VOLUME" &> /dev/null; then | |
echo "Error: Volume '$VOLUME' does not exist." | |
exit 1 | |
fi | |
# 备份 Volume 到指定文件 | |
docker run --rm -v "${VOLUME}":/volume -v "$(pwd)":/backup busybox tar -czf "/backup/${FILE}" -C /volume . | |
if [ $? -eq 0 ]; then | |
echo "Backup successful. File saved as ${FILE}." | |
else | |
echo "Backup failed." | |
fi | |
;; | |
restore) | |
VOLUME=$3 | |
FILE=$2 | |
# 检查备份文件是否存在 | |
if [ ! -f "$FILE" ]; then | |
echo "Error: File '$FILE' does not exist." | |
exit 1 | |
fi | |
# 恢复备份到 Volume | |
docker volume create "$VOLUME" > /dev/null | |
docker run --rm -v "${VOLUME}":/volume -v "$(pwd)":/backup busybox tar -xzf "/backup/${FILE}" -C /volume | |
if [ $? -eq 0 ]; then | |
echo "Restore successful. Data restored to volume '${VOLUME}'." | |
else | |
echo "Restore failed." | |
fi | |
;; | |
*) | |
echo "Invalid command. Use 'backup' or 'restore'." | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment