diff --git a/backup_named_volumes.sh b/backup_named_volumes.sh index c7eb8cd..2e58f9e 100644 --- a/backup_named_volumes.sh +++ b/backup_named_volumes.sh @@ -10,22 +10,26 @@ if [[ ! -f "$COMPOSE_FILE" ]]; then exit 1 fi -# Determine the project name (same as docker-compose uses) +# Determine project name (Docker Compose style) PROJECT_NAME=$(basename "$WORKDIR") - echo "📦 Working in (${PROJECT_NAME})" -# Get all services using yq +# Get original user details (in case script is run via sudo -E or similar) +ORIGINAL_USER="${SUDO_USER:-$USER}" +ORIGINAL_UID=$(id -u "$ORIGINAL_USER") +ORIGINAL_GID=$(id -g "$ORIGINAL_USER") + +# Get services SERVICE_NAMES=$(yq e '.services | keys | .[]' "$COMPOSE_FILE") for SERVICE in $SERVICE_NAMES; do echo "🔍 Found service (${SERVICE})" - # Get the volumes for the service + # Get service volumes VOLUMES=$(yq e ".services.${SERVICE}.volumes[]" "$COMPOSE_FILE" 2>/dev/null || true) while IFS= read -r VOLUME; do - # Clean up quotes and whitespace + # Clean up quotes/whitespace VOLUME=$(echo "$VOLUME" | sed 's/^"//;s/"$//;s/^[[:space:]]*//;s/[[:space:]]*$//') # Skip bind mounts @@ -33,30 +37,30 @@ for SERVICE in $SERVICE_NAMES; do continue fi - # Get the source volume name (before colon) SOURCE=$(echo "$VOLUME" | cut -d':' -f1) - echo "📁 Found named volume (${SOURCE})" - # Prompt the user - read -rp "→ Would you like to tar.gz and save to this location as ${SOURCE}.tar.gz? (Y/n) " REPLY + read -rp "→ Tar.gz and save as ${SOURCE}.tar.gz? (Y/n) " REPLY REPLY=${REPLY:-Y} if [[ "$REPLY" =~ ^[Yy]$ ]]; then VOLUME_PATH="/var/lib/docker/volumes/${PROJECT_NAME}_${SOURCE}/_data" + OUTPUT_FILE="${WORKDIR}/${SOURCE}.tar.gz" - if [[ ! -d "$VOLUME_PATH" ]]; then - echo "⚠️ Volume path $VOLUME_PATH not found! Skipping..." + if ! sudo test -d "$VOLUME_PATH"; then + echo "⚠️ Volume path not found: $VOLUME_PATH" continue fi - OUTPUT_FILE="${WORKDIR}/${SOURCE}.tar.gz" + echo "📦 Backing up $VOLUME_PATH → $OUTPUT_FILE" - echo "📦 Backing up $VOLUME_PATH to $OUTPUT_FILE" + # Use sudo to read, but write file as your user + sudo tar -czf "$OUTPUT_FILE" -C "$VOLUME_PATH" . - tar -czf "$OUTPUT_FILE" -C "$VOLUME_PATH" . + # Fix ownership in case sudo did anything funny + chown "$ORIGINAL_UID:$ORIGINAL_GID" "$OUTPUT_FILE" - echo "✅ Backup complete: $OUTPUT_FILE" + echo "✅ Backup done: $OUTPUT_FILE" else echo "⏭️ Skipping ${SOURCE}" fi