Skip to content

Instantly share code, notes, and snippets.

@quasa0
Last active May 20, 2025 23:42
Show Gist options
  • Save quasa0/539b8e95b746fcf30971bfdf96ab2e7d to your computer and use it in GitHub Desktop.
Save quasa0/539b8e95b746fcf30971bfdf96ab2e7d to your computer and use it in GitHub Desktop.
Backup your .zsh_history .zshrc and other things using crontab -e
#!/bin/zsh
# To schedule this via crontab do:
# Put this file somewhere, e.g. ~/bin/backup_zsh_history.sh
# crontab -e
# Add "0 * * * * /bin/zsh /Users/q/bin/backup_zsh_history.sh" to backup every 1 hour
# Or "* * * * * /bin/zsh /Users/q/bin/backup_zsh_history.sh" to backup every 1 min
# Script to backup specified configuration files using Git
# Copies the files to a Git repository and commits the changes.
# Array of file basenames to backup (relative to /Users/q)
FILES_TO_BACKUP=("/Users/q/.zsh_history" "/Users/q/.zshrc")
BACKUP_REPO_DIR="/Users/q/.history_backups"
# Create the backup directory if it doesn't exist
mkdir -p "$BACKUP_REPO_DIR"
# Change to the backup repository directory
cd "$BACKUP_REPO_DIR"
# Initialize the repository if it doesn't exist
if [ ! -d ".git" ]; then
git init
fi
# Copy and add files
for SOURCE_FILE in "${FILES_TO_BACKUP[@]}"; do
file_basename=$(basename "$SOURCE_FILE") # Extract basename for destination
DEST_FILE_IN_REPO="$BACKUP_REPO_DIR/$file_basename"
if [ -f "$SOURCE_FILE" ]; then
cp "$SOURCE_FILE" "$file_basename" # Use file_basename as dest since we are in BACKUP_REPO_DIR
git add "$file_basename"
echo "Copied and staged $file_basename"
else
echo "Warning: Source file $SOURCE_FILE does not exist. Skipping."
fi
done
# Commit the changes with a timestamp
# Check if there are changes to commit to avoid empty commits
if ! git diff --staged --quiet; then
# commit_message="Configuration files backup: $(date +"%Y-%m-%d %H:%M:%S")"
# Optionally, list the files in the commit message
changed_files=$(git diff --staged --name-only)
commit_message="Backup $(echo $changed_files | tr '\n' ' '): $(date +"%Y-%m-%d %H:%M:%S")"
git commit -m "$commit_message"
echo "Configuration files backed up and committed in $BACKUP_REPO_DIR"
git push
else
echo "No changes to tracked files. Nothing to commit."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment