设置git初始化默认分支为main

好久没上传代码到 GitHub 了,前两天新建了一个仓库,然后习惯性的执行 git push origin master  , 过了好一会儿才在 GitHub 页面上看到两个分支:main 和 master。

这两天陆陆续续出现好几次,网上查了一下才知道从10月份起,GitHub 的默认分支名不再是master,而是main。据说是因为master这个词和种族主义有关系,现在的人真是玻璃心啊。

git 初始化默认分支名是master,每次新建仓库都要改默认分支名很麻烦,就查了一下设置 git 初始化分支名的方法,找到两种解决办法:

  • 初始化后切换分支 >> https://stackoverflow.com/a/42871621

    As you noticed, there is no parameter for git init for the branch name, so two commands will have to do.

    git init
    git checkout -b trunk
    

    This creates a new repository with trunk as the current branch instead of master. The branch master does not actually exist–the branches don’t get created until they have at least one commit. Until the branch gets created, the branch only exists in .git/HEAD, which explains why the master branch will disappear when you switch to trunk.

    If you’ve already committed, you can run git branch -m instead:

    git init
    touch file.txt
    git add file.txt
    git commit -m 'commit 1'
    git branch -m trunk
    

    This renames the branch from master to trunk once it’s created.

    This does seem a bit clunky since the mechanism is different depending on whether the repository is empty, but it works.

  • 升级 git 使用 git 全局配置 >> https://stackoverflow.com/a/63136920

    Since Git 2.28 (released July 27, 2020) a new configuration option, init.defaultBranch is being introduced to replace the hard-coded term master.

    Default remains to master!

    The user can override the default value of the configuration variable with:

    $ git config --global init.defaultBranch main
    

    Read the git doc chapter for further details Introducing init.defaultBranch

    升级 git 还要配置 zsh,太麻烦了,没试。