- Work on multiple branches without switching or stashing.
- Avoids dirty working directory issues.
- Ideal for parallel development, review, testing, and fixes.
- Keeps
main
worktree clean and focused.
Organize by task type and ticket ID or purpose:
monorepo/
βββ .git/
βββ worktrees/
β βββ feature/
β β βββ ABC-123/
β βββ bugfix/
β β βββ BUG-456/
β βββ review/
β β βββ PR-789/
Place this in your repo root to create structured, isolated worktrees easily.
#!/bin/bash
# === Validate Input ===
if [ -z "$1" ] || [ -z "$2" ]; then
echo "β Error: Missing required arguments."
echo "Usage: $0 <type> <name>"
echo "Example: $0 feature XYZ-123"
echo "Allowed types: feature, bugfix, review, misc"
exit 1
fi
TYPE=$1
NAME=$2
BRANCH="$TYPE/$NAME"
DIR="./worktrees/$TYPE/$NAME"
BASE_BRANCH="origin/release"
# === Check if branch already exists ===
if git show-ref --verify --quiet "refs/heads/$BRANCH"; then
echo "β οΈ Local branch '$BRANCH' already exists."
echo " You can delete it with: git branch -D $BRANCH"
exit 1
fi
# === Ensure base branch exists ===
git fetch origin
if ! git show-ref --verify --quiet "refs/remotes/$BASE_BRANCH"; then
echo "β Error: $BASE_BRANCH does not exist."
exit 1
fi
# === Create directory structure ===
mkdir -p "$DIR"
# === Create worktree ===
echo "π§ Creating worktree..."
git worktree add "$DIR" -b "$BRANCH" "$BASE_BRANCH"
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "β Failed to create worktree."
exit 1
fi
echo "β
Worktree created:"
echo "- Branch: $BRANCH (based on $BASE_BRANCH)"
echo "- Directory: $DIR"
β‘οΈ Usage:
./new-worktree.sh feature XYZ-123
git fetch origin
git rebase origin/main
git fetch origin
git merge origin/main
git pull --rebase origin main
Command | Purpose |
---|---|
git worktree list |
List all active worktrees |
git worktree remove <path> |
Remove a worktree (when done) |
git branch -D <branch> |
Delete branch after removing worktree |
mkdir -p ./worktrees/... |
Ensure path exists before worktree add |
- Branch already exists: Check with
git branch
; delete if needed. - Worktree already active: Check with
git worktree list
. - Wrong path: Always use relative paths like
./worktrees/...
from repo root. - Base branch doesnβt exist: Run
git fetch origin
before worktree creation.
- Keep your base
main
orrelease
branch clean. - Use structured directories under
./worktrees/
. - Automate common setups to reduce context switching.
- Rebase often to avoid nasty merge conflicts.
- Clean up unused worktrees and branches.
Let me know if you want to turn this into a markdown file (README.md
) or automate this further with aliases, hooks, or prompts.