petersohn
petersohn

Reputation: 11720

git branch -f and git checkout in one step

Sometimes I need to move a branch to my current commit. There is two ways I can do it:

git checkout foo
git reset --hard HEAD@{1}

I don't like this because this way I have to change the working directory twice. A better option is this:

git branch -f foo
git checkout foo

This is better, but I would like to do it in one step, just like when I switch to a new branch git checkout -b. Unfortunately, git checkout -f -b foo doesn't work.

Upvotes: 2

Views: 549

Answers (3)

Scott Weldon
Scott Weldon

Reputation: 10217

You could use an Alias. Add this to your Git config file:

[alias]
  branchout = "! git branch -f $1; git checkout $1; true"

Then use with:

git branchout foo

Upvotes: 1

Basilio German
Basilio German

Reputation: 1819

You can do as Scott Weldon suggests, by editing your Git config file to create an alias, but you can also add an alias with git config:

git config alias.branchout "! git branch -f $1; git checkout $1; true"

And then use it the same way:

git branchout foo

Note that you can always change the command name branchout to anything you want, to make it even shorter to type.

Upvotes: 2

torek
torek

Reputation: 487725

The alias methods are fine, but note that git checkout -B does the same thing as a single atomic transaction:

If -B is given, <new_branch> is created if it doesn't exist; otherwise, it is reset. This is the transactional equivalent of

    $ git branch -f <branch> [<start point>]
    $ git checkout <branch>

that is to say, the branch is not reset/created unless "git checkout" is successful.

(It's not clear why this is specifically spelled -B rather than -f -b, but the point is that this is built in to git checkout.)

Upvotes: 4

Related Questions