How to get a git's branch with fuzzy finder?

5.6k Views Asked by At

I found git examples with fzf(fuzzy finder) and they does work great. like:

# fbr - checkout git branch
fbr() {
  local branches branch
  branches=$(git branch -vv) &&
  branch=$(echo "$branches" | fzf +m) &&
  git checkout $(echo "$branch" | awk '{print $1}' | sed "s/.* //")
}

# fbr - checkout git branch (including remote branches)
fbr() {
  local branches branch
  branches=$(git branch --all | grep -v HEAD) &&
  branch=$(echo "$branches" |
           fzf-tmux -d $(( 2 + $(wc -l <<< "$branches") )) +m) &&
  git checkout $(echo "$branch" | sed "s/.* //" | sed "s#remotes/[^/]*/##")
}

I have this in my .bashrc

bind '"\C-b": "fbr \n"'

After I press Ctrl-b I get to choose a git's branch and it switches right after I press enter, but is there a way to type something first like git push staging (and then get the list of branches and put selected branch right where the cursor was before calling the list of branches, and then I press enter to push the selected branch to staging)

Ex: git push staging (Ctrl-b - choose a branch) and I want to get this output - git push staging selected_branch

2

There are 2 best solutions below

1
Junegunn Choi On BEST ANSWER

These are the key bindings I use in bash

  • CTRL-GCTRL-F - Files listed in git status
  • CTRL-GCTRL-B - Branches
  • CTRL-GCTRL-T - Tags
  • CTRL-GCTRL-H - Commit hashes
  • CTRL-GCTRL-R - Remotes

Note that redraw-current-line is not necessary if you're on tmux.

is_in_git_repo() {
  git rev-parse HEAD > /dev/null 2>&1
}

gf() {
  is_in_git_repo &&
    git -c color.status=always status --short |
    fzf --height 40% -m --ansi --nth 2..,.. | awk '{print $2}'
}

gb() {
  is_in_git_repo &&
    git branch -a -vv --color=always | grep -v '/HEAD\s' |
    fzf --height 40% --ansi --multi --tac | sed 's/^..//' | awk '{print $1}' |
    sed 's#^remotes/[^/]*/##'
}

gt() {
  is_in_git_repo &&
    git tag --sort -version:refname |
    fzf --height 40% --multi
}

gh() {
  is_in_git_repo &&
    git log --date=short --format="%C(green)%C(bold)%cd %C(auto)%h%d %s (%an)" --graph |
    fzf --height 40% --ansi --no-sort --reverse --multi | grep -o '[a-f0-9]\{7,\}'
}

gr() {
  is_in_git_repo &&
    git remote -v | awk '{print $1 " " $2}' | uniq |
    fzf --height 40% --tac | awk '{print $1}'
}

bind '"\er": redraw-current-line'
bind '"\C-g\C-f": "$(gf)\e\C-e\er"'
bind '"\C-g\C-b": "$(gb)\e\C-e\er"'
bind '"\C-g\C-t": "$(gt)\e\C-e\er"'
bind '"\C-g\C-h": "$(gh)\e\C-e\er"'
bind '"\C-g\C-r": "$(gr)\e\C-e\er"'
1
legendmohe On

If you're using Windows, try git checkout @(git branch -a | fzf).trim()