Skip to content

Instantly share code, notes, and snippets.

@faytranevozter
Created January 20, 2025 01:44
Show Gist options
  • Select an option

  • Save faytranevozter/e1144406175a16417fa5d9f337dad90b to your computer and use it in GitHub Desktop.

Select an option

Save faytranevozter/e1144406175a16417fa5d9f337dad90b to your computer and use it in GitHub Desktop.
#!/bin/bash
# Define usage function
usage() {
echo "Usage: $0 {backup|restore} -v <volume_name> -f <file_path>"
echo "Options:"
echo " backup: Back up the specified Docker volume to a tarball."
echo " restore: Restore a Docker volume from a tarball."
echo " -v <volume_name>: Name of the Docker volume."
echo " -f <file_path>: Path to the tarball file."
exit 1
}
# Ensure at least 4 arguments are provided
if [ "$#" -lt 4 ]; then
usage
fi
# Parse command-line arguments
COMMAND=$1
shift
while getopts ":v:f:" opt; do
case ${opt} in
v) VOLUME_NAME=${OPTARG} ;;
f) FILE_PATH=${OPTARG} ;;
*) usage ;;
esac
done
# Ensure volume name and file path are set
if [ -z "$VOLUME_NAME" ] || [ -z "$FILE_PATH" ]; then
usage
fi
# Check if the Docker volume exists
check_volume_exists() {
if ! docker volume inspect "$VOLUME_NAME" > /dev/null 2>&1; then
echo "Error: Docker volume '$VOLUME_NAME' does not exist."
exit 1
fi
}
# Backup function
backup_volume() {
echo "Backing up Docker volume '$VOLUME_NAME' to '$FILE_PATH'..."
docker run --rm \
-v "${VOLUME_NAME}:/volume" \
-v "$(dirname "$FILE_PATH"):/backup" \
alpine \
tar -czf "/backup/$(basename "$FILE_PATH")" -C /volume .
echo "Backup completed."
}
# Restore function
restore_volume() {
echo "Restoring Docker volume '$VOLUME_NAME' from '$FILE_PATH'..."
docker run --rm \
-v "${VOLUME_NAME}:/volume" \
-v "$(dirname "$FILE_PATH"):/backup" \
alpine \
sh -c "rm -rf /volume/* && tar -xzf /backup/$(basename "$FILE_PATH") -C /volume"
echo "Restore completed."
}
# Execute the specified command
case $COMMAND in
backup)
check_volume_exists
backup_volume
;;
restore)
check_volume_exists
restore_volume
;;
*)
usage
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment