Skip to content

Instantly share code, notes, and snippets.

@vikrum
Created June 17, 2026 15:59
Show Gist options
  • Select an option

  • Save vikrum/7b36145ee54219a25ccba7831736ab0e to your computer and use it in GitHub Desktop.

Select an option

Save vikrum/7b36145ee54219a25ccba7831736ab0e to your computer and use it in GitHub Desktop.
worktree helpers
# newt: fresh worktree off origin/main (ignores current branch/dirty state) + cd into it
function newt() {
local toplevel parent repo branch newdir
toplevel=$(git rev-parse --show-toplevel 2>/dev/null) || {
echo "newt: not inside a git repository" >&2
return 1
}
repo=$(basename "$(dirname "$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)")")
parent=$(dirname "$toplevel")
branch="$(whoami)-$(date +%s)"
newdir="$parent/$repo-$branch"
echo "newt: fetching origin/main..." >&2
git fetch origin main || {
echo "newt: 'git fetch origin main' failed" >&2
return 1
}
git worktree add -b "$branch" "$newdir" origin/main || {
echo "newt: failed to create worktree at $newdir" >&2
return 1
}
cd "$newdir" && echo "newt: now in $newdir on branch $branch" >&2
}
# rmwt: remove the current worktree and delete its local branch (cleanup after newt)
function rmwt() {
local toplevel branch common main_toplevel
toplevel=$(git rev-parse --show-toplevel 2>/dev/null) || {
echo "rmwt: not inside a git repository" >&2
return 1
}
common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)
main_toplevel=$(dirname "$common")
branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [[ "$toplevel" == "$main_toplevel" ]]; then
echo "rmwt: refusing to remove the main worktree ($toplevel)" >&2
return 1
fi
if [[ "$branch" == "main" ]]; then
echo "rmwt: refusing, current branch is 'main'" >&2
return 1
fi
cd "$main_toplevel" || return 1
git worktree remove "$toplevel" || {
echo "rmwt: 'git worktree remove' failed; if it's just untracked/dirty files run: git worktree remove --force $toplevel" >&2
cd "$toplevel" 2>/dev/null
return 1
}
git branch -D "$branch" && echo "rmwt: removed worktree $toplevel and branch $branch" >&2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment