Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Last active October 20, 2025 03:59
Show Gist options
  • Select an option

  • Save YuanLiou/baa8349970e9d0f904f3b9e42017e1d4 to your computer and use it in GitHub Desktop.

Select an option

Save YuanLiou/baa8349970e9d0f904f3b9e42017e1d4 to your computer and use it in GitHub Desktop.
auto_archive_to_gdrive.sh
#!/bin/bash
# ==============================================================================
#
# Title: auto_archive_to_gdrive.sh
# Description: A non-interactive script to compress a folder and move it to
# a destination. Designed to be run by an automated service
# like launchd on macOS.
# Author: Gemini and ray liu
#
# Usage: ./auto_archive_to_gdrive.sh /path/to/source/folder /path/to/destination/folder
#
# ==============================================================================
# --- Step 1: Validate Inputs ---
if [ -z "$1" ] || [ -z "$2" ]; then
echo "❌ Error: Missing arguments."
echo "Usage: $0 /path/to/source/folder /path/to/destination/folder"
exit 1
fi
SOURCE_FOLDER="$1"
GDRIVE_PATH="$2"
# Check if the provided paths are valid directories.
if [ ! -d "$SOURCE_FOLDER" ]; then
echo "❌ Error: Source '$SOURCE_FOLDER' is not a valid directory."
exit 1
fi
if [ ! -d "$GDRIVE_PATH" ]; then
echo "❌ Error: Destination '$GDRIVE_PATH' is not a valid directory."
exit 1
fi
# --- Step 2: Prepare Filenames and Paths ---
SOURCE_FOLDER_CLEAN="${SOURCE_FOLDER%/}"
FOLDER_BASENAME=$(basename "$SOURCE_FOLDER_CLEAN")
TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
ZIP_FILENAME="${FOLDER_BASENAME}_${TIMESTAMP}.zip"
echo "================================================="
echo "Starting archive job at $(date)"
echo "πŸ“‚ Source folder: $SOURCE_FOLDER_CLEAN"
echo "πŸ“¦ Archive name will be: $ZIP_FILENAME"
echo "🎯 Destination folder: $GDRIVE_PATH"
echo ""
# --- Step 3: Compress and Move ---
echo "βš™οΈ Compressing '$FOLDER_BASENAME'..."
# Create the zip file in a temporary location first.
# This prevents issues with zipping directly into a cloud-synced folder.
ZIP_TEMP_PATH="/tmp/${ZIP_FILENAME}"
# 'cd' into the parent directory of the source to ensure a clean archive structure without parent paths.
SOURCE_PARENT_DIR=$(dirname "$SOURCE_FOLDER_CLEAN")
(cd "$SOURCE_PARENT_DIR" && zip -r -q "$ZIP_TEMP_PATH" "$(basename "$SOURCE_FOLDER_CLEAN")")
if [ $? -ne 0 ]; then
echo "❌ Error: Compression failed."
exit 1
fi
echo "βœ… Compression successful!"
echo "🚚 Moving '$ZIP_FILENAME' to destination..."
# Now, move the created zip file to its final destination.
mv "$ZIP_TEMP_PATH" "$GDRIVE_PATH/"
if [ $? -ne 0 ]; then
echo "❌ Error: Failed to move the file."
rm "$ZIP_TEMP_PATH"
exit 1
fi
echo "✨ All done! Your archive has been successfully moved."
echo "πŸ“ Final location: $GDRIVE_PATH/$ZIP_FILENAME"
echo "Job finished at $(date)"
echo "================================================="
echo ""
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment