Skip to content

Instantly share code, notes, and snippets.

@robsimpsondev
Forked from dhh/agent-git-trees.sh
Last active February 11, 2026 17:19
Show Gist options
  • Select an option

  • Save robsimpsondev/4bcff48696c4c062fd6780cf3b05a37d to your computer and use it in GitHub Desktop.

Select an option

Save robsimpsondev/4bcff48696c4c062fd6780cf3b05a37d to your computer and use it in GitHub Desktop.
Create and delete git worktrees quickly
confirm() {
# call with a prompt string or use a default
read -r -p "${1:-Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
true
;;
*)
false
;;
esac
}
# Create a new worktree and branch from within current git directory.
gwa() {
if [ $# -eq 0 ]; then
echo "Usage: gwa [branch name]"
return 1
fi
local branch="$1"
local base="$(basename "$PWD")"
local new="../${base}--${branch}"
git worktree add -b "$branch" "$new"
cd "$new"
}
# Remove worktree and branch from within active worktree directory.
gwd() {
if confirm "Remove current worktree and branch? [y/N]"; then
local cwd base branch root
cwd="$(pwd)"
worktree="$(basename "$cwd")"
# split on first `--`
root="${worktree%%--*}"
branch="${worktree#*--}"
# Protect against accidentially nuking a non-worktree directory
if [[ "$root" != "$worktree" ]]; then
cd "../$root"
git worktree remove "$worktree" --force
git branch -D "$branch"
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment