Skip to content

Instantly share code, notes, and snippets.

@sakkas-zendesk
Last active October 10, 2023 06:30
Show Gist options
  • Save sakkas-zendesk/ffe6dff74d1998322fdb2ac853bb85be to your computer and use it in GitHub Desktop.
Save sakkas-zendesk/ffe6dff74d1998322fdb2ac853bb85be to your computer and use it in GitHub Desktop.

How to easily checkout branches into new worktree directories

Worktree-demo

See the gif file below if the gist does not render the screen capture in this markdown document.

  1. git worktree-add <branch-name> to add the worktree.
  2. gcd and hit enter, let fzf to choose and cd into the directory.
  3. When you're done, git worktree-remove-picked to remove selected worktree and the files from your disk.

Assumes you have fzf and gnu-utils (awk, sed, but ideally not the bsd/mac one) installed.

You can add below to your .gitconfig under alias section

[alias]
    # worktree
    wl = worktree list
    repo-dir = rev-parse --show-toplevel
    repo-name = "!sh -c 'basename $(git repo-dir $1) -- $1'"
    worktree-add = "!sh -c 'git remote show | grep origin > /dev/null 2>&1 && git fetch origin \"$1\" ; git worktree add \"$HOME/Dev/worktrees/$(git repo-name)/$1\" \"$1\"' -- $1"
    worktree-remove-picked = "!sh -c 'git worktree remove $(git worktree-pick)'"
    worktree-pick = "!sh -c 'git worktree list | fzf | awk \"{print \\$3}\" | sed \"s/^.//;s/.$//\" '"
    worktree-pick-dir = "!sh -c 'git worktree list | fzf | awk \"{print \\$1}\"'"

And this to your shell profile / rcfile or dotfiles import, like .bashrc

alias gcd='cd $(git worktree-pick-dir)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment