Skip to content

Instantly share code, notes, and snippets.

@james-livefront
Created February 23, 2026 21:57
Show Gist options
  • Select an option

  • Save james-livefront/414b40f5f8b5124fa742858802223c02 to your computer and use it in GitHub Desktop.

Select an option

Save james-livefront/414b40f5f8b5124fa742858802223c02 to your computer and use it in GitHub Desktop.
gco: git checkout wrapper that auto-cds into an existing worktree when a branch is already checked out there
# gco - git checkout wrapper that automatically cds into an existing worktree
# when the branch is already checked out there.
#
# Usage: gco <branch> (drop-in replacement for git checkout)
#
# Instead of:
# fatal: 'fix/my-branch' is already used by worktree at '/path/to/worktree'
#
# gco will cd directly into the worktree.
gco() {
local output exit_code worktree_path
output=$(git checkout "$@" 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
echo "$output"
return 0
fi
# Extract path from: fatal: 'branch' is already used by worktree at '/path'
worktree_path=$(echo "$output" | sed -n "s/.*worktree at '\\([^']*\\)'.*/\\1/p")
if [ -n "$worktree_path" ]; then
echo "Branch is checked out in worktree. Switching to: $worktree_path"
cd "$worktree_path" || return 1
return 0
fi
echo "$output" >&2
return $exit_code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment