Skip to content

Instantly share code, notes, and snippets.

@MrSunshyne
Created February 28, 2025 11:05
Show Gist options
  • Save MrSunshyne/bd4fef42a31ad311a82eb458b5734614 to your computer and use it in GitHub Desktop.
Save MrSunshyne/bd4fef42a31ad311a82eb458b5734614 to your computer and use it in GitHub Desktop.
A helper for using worktrees in any repo
# Make sure the repo is cloned with --bare
# Guide: https://nicknisi.com/posts/git-worktrees/
# Paste the following in your .zshrc
alias newtree='new-worktree'
new-worktree() {
local branch_name="$1"
local repo_dir="PATH TO YOUR REPO"
local worktree_dir="$repo_dir/$branch_name"
if [[ -d "$worktree_dir" ]]; then
echo "Worktree '$branch_name' already exists."
cd "$worktree_dir" || {
echo "Failed to navigate to existing worktree '$worktree_dir'"
return 1
}
echo "Navigated to existing worktree '$worktree_dir'."
return 0
fi
cd "$repo_dir" || {
echo "Failed to navigate to $repo_dir"
return 1
}
git fetch origin || {
echo "Failed to fetch from origin"
return 1
}
if git branch -r | grep -q "origin/$branch_name"; then
# Remote branch exists
git worktree add "$branch_name" "origin/$branch_name" || {
echo "Failed to create worktree '$branch_name'"
return 1
}
else
# Remote branch does not exist, create it locally and push from worktree
git worktree add "$branch_name" || {
echo "Failed to create worktree '$branch_name'"
return 1
}
cd "$worktree_dir" || {
echo "Failed to navigate to '$worktree_dir'"
return 1
}
git checkout -b "$branch_name" || {
echo "Failed to create local branch '$branch_name'"
return 1
}
# Check if remote branch exists again after local creation
git push -u origin "$branch_name" 2>/dev/null || {
if git branch -r | grep -q "origin/$branch_name"; then
echo "Remote branch was created by another user, setting upstream"
else
echo "Failed to push branch '$branch_name' to origin"
return 1
fi
}
fi
cd "$worktree_dir" || {
echo "Failed to navigate to '$worktree_dir'"
return 1
}
git branch --set-upstream-to=origin/"$branch_name" "$branch_name" || {
echo "Failed to set upstream for branch '$branch_name'"
return 1
}
echo "Worktree '$branch_name' created and upstream set."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment