Skip to content

Instantly share code, notes, and snippets.

@naiquevin
Last active December 31, 2024 06:15
Show Gist options
  • Save naiquevin/a703115ba46aa35bfbd7574d2df86097 to your computer and use it in GitHub Desktop.
Save naiquevin/a703115ba46aa35bfbd7574d2df86097 to your computer and use it in GitHub Desktop.
Script to backup stashes in a git repository

Usage

find . -name '.git' | xargs dirname | xargs -P 4 -n 1 -I % ./backup-stashes.sh % /tmp/stash-backups

Note

Much of the code is generated by Claude Sonnet 3.5. Exercise caution by going through it before executing.

#!/bin/bash
# Check if correct number of arguments is provided
if [ $# -ne 2 ]; then
echo "Usage: $0 <git-repo-path> <parent-directory>"
exit 1
fi
REPO_PATH="$1"
PARENT_DIR="$2"
# Get the source directory name
REPO_NAME=$(basename "$REPO_PATH")
TARGET_DIR="$PARENT_DIR/$REPO_NAME"
# Check if repository path exists and is a git repository
if [ ! -d "$REPO_PATH/.git" ]; then
echo "Error: $REPO_PATH is not a git repository"
exit 1
fi
# Check if parent directory exists
if [ ! -d "$PARENT_DIR" ]; then
echo "Error: Parent directory $PARENT_DIR does not exist"
exit 1
fi
# Check if target directory already exists
if [ -d "$TARGET_DIR" ]; then
echo "Error: Target directory $TARGET_DIR already exists"
exit 1
fi
# Change to repository directory
cd "$REPO_PATH" || exit 1
# Create temporary file for stash list
TEMP_FILE=$(mktemp)
git stash list > "$TEMP_FILE"
# Check if there are any stashes
if [ ! -s "$TEMP_FILE" ]; then
echo "No stashes found in repository"
rm "$TEMP_FILE"
exit 0
fi
# Create target directory only if we have stashes
mkdir -p "$TARGET_DIR"
# Move stash list to final location
mv "$TEMP_FILE" "$TARGET_DIR/index.txt"
# Counter for stash number
counter=0
# Loop through each stash
while IFS= read -r stash; do
# Create diff file for each stash
git stash show -p "stash@{$counter}" > "$TARGET_DIR/$counter"
# Check if diff creation was successful
if [ $? -ne 0 ]; then
echo "Error: Failed to create diff for stash $counter"
continue
fi
# Increment counter
((counter++))
done < "$TARGET_DIR/index.txt"
echo "Successfully backed up $counter stash(es) to $TARGET_DIR"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment