cernius
cernius

Reputation: 41

How to write alias for bash command that finds and checkouts a branch

I'd like to create an alias or a function to find a branch by part of its name and checkout it. It can be done with git branch | grep <search-string> | xargs git checkout but it is cumbersome to write it every time. I tried to write a function (below) but it looks like even the git branch part does not work in it.

Any advises on how it could be done?

function grep_checkout {
        local checkout_command="git branch | grep $1 | xargs git checkout"

        echo $($checkout_command)
}

Upvotes: 0

Views: 194

Answers (2)

padawin
padawin

Reputation: 4476

I use fzf for that, I have the following alias:

alias gco='git checkout $(git branch | grep -v $(git rev-parse --abbrev-ref HEAD) | fzf)'

It is described on the project page how to set it up: https://github.com/junegunn/fzf

Then, I type gco, press return, then I find my branch and return again to run the checkout.

Upvotes: 2

Drako
Drako

Reputation: 768

you write same way as you write any other aliases:

alias fcb = 'git branch | grep <search-string> | xargs git checkout '

whenever you need to run this command use fcb; you can write this in your main or profile bash config so you don't have to set it on every run of the console.

PS. I don't have nix machine available so did not check if the command actually works - just re-used what you provided, hoping it does what you want.

Upvotes: 0

Related Questions