#!/bin/bash set -euo pipefail # Clean up git worktrees # # Usage: # ./cleanup-worktrees.sh # Remove specific worktree # ./cleanup-worktrees.sh # Remove all worktrees in directory # ./cleanup-worktrees.sh --force # Force remove even if dirty FORCE=false if [ "$1" = "--force" ]; then FORCE=true shift fi TARGET="$1" REPO_PATH=$(git rev-parse --show-toplevel 2>/dev/null || pwd) cd "$REPO_PATH" remove_worktree() { local worktree_path="$1" if [ ! -d "$worktree_path" ]; then return 0 fi if [ "$FORCE" = true ]; then git worktree remove "$worktree_path" --force 2>/dev/null || true else git worktree remove "$worktree_path" 2>/dev/null || true fi } # Check if target is a directory containing multiple worktrees if [ -d "$TARGET" ]; then # Check if it's a worktree itself or a directory of worktrees if git worktree list | grep -q "$TARGET\$"; then # It's a single worktree remove_worktree "$TARGET" else # It's a directory, remove all worktrees inside for worktree in "$TARGET"/*; do if [ -d "$worktree" ]; then remove_worktree "$worktree" fi done # Try to remove the directory if empty rmdir "$TARGET" 2>/dev/null || true fi else echo "Error: Path does not exist: $TARGET" >&2 exit 1 fi