Skip to content

Instantly share code, notes, and snippets.

@adamhancock
Last active July 27, 2025 08:06
Show Gist options
  • Save adamhancock/9586cc5526b472a786b2d6e4045464b5 to your computer and use it in GitHub Desktop.
Save adamhancock/9586cc5526b472a786b2d6e4045464b5 to your computer and use it in GitHub Desktop.
Create and open worktree
# Git Worktree Creator Function
# Usage: worktree <branch-name>
worktree() {
# Check if branch name is provided
if [ $# -eq 0 ]; then
echo "Usage: worktree <branch-name>"
echo "Example: worktree feature/new-feature"
return 1
fi
local BRANCH_NAME="$1"
# Replace forward slashes with hyphens for directory name
local SAFE_BRANCH_NAME=$(echo "$BRANCH_NAME" | sed 's/\//-/g')
local WORKTREE_PATH="../assurix-${SAFE_BRANCH_NAME}"
echo "Creating worktree for branch: $BRANCH_NAME"
echo "Worktree path: $WORKTREE_PATH"
# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "Error: Not in a git repository"
return 1
fi
# Check if the worktree directory already exists
if [ -d "$WORKTREE_PATH" ]; then
echo "Error: Directory $WORKTREE_PATH already exists"
return 1
fi
# Update main branch to latest
echo "Updating main branch..."
git fetch origin
git checkout main
git pull origin main
# Create the worktree from main branch
echo "Creating worktree from main branch..."
git worktree add "$WORKTREE_PATH" main
# Navigate to the new worktree
cd "$WORKTREE_PATH"
# Create and checkout the new branch
echo "Creating and checking out branch: $BRANCH_NAME"
git checkout -b "$BRANCH_NAME"
# Open in VS Code
echo "Opening in VS Code..."
code .
echo "✅ Worktree created successfully!"
echo "📁 Location: $WORKTREE_PATH"
echo "🌿 Branch: $BRANCH_NAME"
}
# Optional: Add an alias for even shorter usage
alias wt='worktree'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment