Skip to content

Instantly share code, notes, and snippets.

@danielrose7
Last active March 24, 2026 21:15
Show Gist options
  • Select an option

  • Save danielrose7/15d7c36e4d1ddec87f221ad9285ea52a to your computer and use it in GitHub Desktop.

Select an option

Save danielrose7/15d7c36e4d1ddec87f221ad9285ea52a to your computer and use it in GitHub Desktop.
Worktree-aware branch switcher: cd to existing worktree instead of failing
# Worktree-aware branch switcher
#
# The problem: git won't let you checkout a branch that's already open in a
# worktree. The error message tells you exactly where to go — so why not just
# go there automatically?
#
# $ git checkout some-branch
# fatal: 'some-branch' is already checked out at '/Users/dan/work/admin.worktrees/some-branch'
#
# Instead of copying that path, this alias catches the error and cd's there.
# Branch names are easy to find (GitHub PR, Linear ticket); worktree paths are not.
#
# Usage: switch [branch] — defaults to "staging"
#
# Note: customize the two hardcoded values below for your setup:
# ~/work/admin — the root git repo (not a worktree)
# "staging" — the default branch when none is provided
switch() {
cd ~/work/admin && nvm use # <-- change to your repo path
local branch="${1:-staging}" # <-- change default branch if needed
local output
output=$(git checkout "$branch" 2>&1)
local exit_code=$?
if [[ $exit_code -eq 0 ]]; then
echo "$output"
elif [[ "$output" =~ "already checked out at '([^']+)'" ]]; then
echo "Already in worktree, switching to: ${match[1]}"
cd "${match[1]}" && nvm use
else
echo "$output" >&2
return $exit_code
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment