find . -name '.git' | xargs dirname | xargs -P 4 -n 1 -I % ./backup-stashes.sh % /tmp/stash-backupsMuch 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" |