git 分支 -f 和 git 一步结帐

git branch -f and git checkout in one step

有时我需要将一个分支移动到我当前的提交。我有两种方法可以做到:

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

我不喜欢这样,因为这样我必须更改工作目录两次。更好的选择是:

git branch -f foo
git checkout foo

这样更好,但我想一步完成,就像我切换到新分支时一样git checkout -b。不幸的是,git checkout -f -b foo 不起作用。

您可以使用别名。将此添加到您的 Git 配置文件中:

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

然后使用:

git branchout foo

您可以按照 Scott Weldon 的建议,通过编辑 Git 配置文件来创建别名,但您也可以使用 git config:

添加别名
git config alias.branchout "! git branch -f ; git checkout ; true"

然后用同样的方法:

git branchout foo

请注意,您可以随时将命令名称 branchout 更改为任何您想要的名称,以使其更短以供键入。

别名方法很好,但请注意 git checkout -B 与单个原子事务做同样的事情:

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.

(不清楚为什么要专门拼写为 -B 而不是 -f -b,但关键是 内置于 git checkout.)