Skip to content

git branch

  1. 将本地仓库初始化,并完成第一次 commit
  2. 在 GitHub 创建一个远程仓库,初始为空,准备接受本地推送

GitHub 远程仓库创建之后的提示页面,给出了要完成从本地仓库到远程仓库推送(第二种方法)的示例代码:

sh
git remote add origin https://github.com/Alowree/Fonts.git
git branch -M main
git push -u origin main

Explain the function of git branch -M main and why it is necessary before the push command.

The command git branch -M main forcefully renames the current branch to main.

  • git branch: The command for branch-related operations.
  • -M: A shortcut for --move --force. It renames the current branch. If a branch named main already exists, it will be overwritten.

Why it's necessary before pushing:

When you create a new repository locally with git init, the default branch name might be master (depending on your Git version). However, new repositories created on GitHub now default to using main.

To avoid a mismatch and to align your local repository with the modern standard used by GitHub, you rename your local master branch to main.

If you didn't do this, your local default branch would be master while the remote's default would be main. When you tried to run git push -u origin main, it would fail with an error like "src refspec main does not match any" because you don't have a local branch named main to push. Renaming it ensures your local and remote branches have the same name, allowing for a clean initial push and proper tracking.

总结一下,示例代码中剩下的三步:

  1. 给本地仓库添加远程仓库
  2. 为本地仓库的当前分支强行重新命名为 main
  3. 推送至远程仓库
最近更新