Skip to content

Instantly share code, notes, and snippets.

@zanieb
Created January 15, 2026 16:09
Show Gist options
  • Select an option

  • Save zanieb/12b08958a82c87cac83eb51b0b43af56 to your computer and use it in GitHub Desktop.

Select an option

Save zanieb/12b08958a82c87cac83eb51b0b43af56 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# gct <branch> - Switch to worktree for branch (create if needed)
set -eu
NAME=${1:-}
if [ -z "$NAME" ]; then
echo "Usage: gct <branch>" >&2
exit 1
fi
# Check for existing worktree
WORKTREE_PATH=$(git worktree list | rg -v "prunable" | rg "\[$NAME\]" | cut -d' ' -f1)
if [ -n "$WORKTREE_PATH" ]; then
if [ -d "$WORKTREE_PATH" ]; then
if [ "$PWD" != "$WORKTREE_PATH" ]; then
cd "$WORKTREE_PATH"
exec "$SHELL"
fi
exit 0
else
# Stale entry
git worktree remove --force "$WORKTREE_PATH"
fi
fi
# Create new worktree
GIT_COMMON_DIR=$(git rev-parse --git-common-dir)
GIT_COMMON_DIR=$(cd "$(dirname "$GIT_COMMON_DIR")" && pwd)/$(basename "$GIT_COMMON_DIR")
REPO_ROOT=$(dirname "$GIT_COMMON_DIR")
REPO_NAME=$(basename "$REPO_ROOT")
NORMALIZED_NAME=${NAME//\//-}
WT_DIR="$REPO_ROOT/../.worktrees/$REPO_NAME/$NORMALIZED_NAME"
# Check if worktree directory already exists at target path
if [ -d "$WT_DIR" ]; then
echo "Switching to existing worktree at: $WT_DIR"
cd "$WT_DIR"
git switch "$NAME" 2>/dev/null || git switch -c "$NAME"
exec "$SHELL"
fi
mkdir -p "$(dirname "$WT_DIR")"
if git branch -la | rg -q "^\s*($NAME|remotes/.*/$NAME)$"; then
git worktree add "$WT_DIR" "$NAME"
else
git worktree add "$WT_DIR" -b "$NAME"
fi
cd "$WT_DIR"
exec "$SHELL"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment