以 github 仓库为例,当远程仓库已经创建

1. 初始化本地仓库

1.1 git init 时设定 branch 为 main

1
git init -b main

也可以在 gitconfig 里配置默认值,要求 git 版本大于 2.28

1.2 Ubuntu 升级 git 版本

1
2
3
# For Ubuntu, this PPA provides the latest stable upstream Git version
add-apt-repository ppa:git-core/ppa
apt update && apt install git

设置默认为 main branch

1
git config --global init.defaultBranch main

查看配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
❯ cat ~/.gitconfig
[include]
path = /etc/git-setup/gitconfig
[core]
editor = vi
[user]
name =
email =
[merge]
tool = vimdiff
[alias]
co = checkout
ci = commit
st = status
br = branch
hist = log --graph --format=format:\"%C(red)%h%C(reset) %C(yellow)%cd%C(reset) | %s %C(green)\\[%an\\]%C(reset)%C(bold blue)%d%C(reset)\" --abbrev-commit --date=short
root = rev-parse --show-toplevel
alias = !git config --list | grep ^alias
head = rev-list -n1 --abbrev-commit HEAD
l = log --stat --color --graph --pretty=format:'%C(bold red)%h%C(reset) - %C(bold green)(%cr)%C(bold blue)<%an>%C(reset) -%C(bold yellow)%d%C(reset) %s' --abbrev-commit
[init]
defaultBranch = main

1.3 修改本地 branch name

1
2
3
4
5
git branch -m master main

$ git branch -m old_branch new_branch # Rename branch locally
$ git push origin :old_branch # Delete the old branch
$ git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote
1
2
3
4
5
6
7
8
9
enwaiax@enwaiax-dev /tmp/test master→ origin/main ⇡
/tmp/test master:main ⇡1


/tmp/test master:main ⇡1
❯ git branch -m master main

enwaiax@enwaiax-dev /tmp/test main ⇡
/tmp/test main ⇡1 ❯

2. commit 本地改动

1
2
3
4
5
$ git add .
# Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.

$ git commit -m "First commit"
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.

3. 设置远程仓库

1
2
3
4
5
$ git remote add origin  <REMOTE_URL>
# Sets the new remote
$ git remote -v
# Verifies the new remote URL

4. 设置与远程仓库同步

1
2
$ git branch --set-upstream-to=origin/<branch> <local_branch>
$ git branch --set-upstream-to=origin/main main

5. Git 相关常用指令

git push origin 与 git push -u origin master 的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
git push origin
将当前分支推送到 origin 主机的对应分支。 其中 origin 可通过 `git remote -v` 查看

❯ git remote -v
origin https://github.com/Chasing66/learn-go-with-tests.git (fetch)
origin https://github.com/Chasing66/learn-go-with-tests.git (push)

如果当前分支只有一个追踪分支,那么主机名都可以省略。

$ git push 如果当前分支与多个主机存在追踪关系,那么这个时候 -u 选项会指定一个默认主机,这样后面就可以不加任何参数使用 git push。

$ git push -u origin master 上面命令将本地的 master 分支推送到 origin 主机,同时指定 origin 为默认主机,后面就可以不加任何参数使用 git push 了。

不带任何参数的 git push,默认只推送当前分支,这叫做 simple 方式。此外,还有一种 matching 方式,会推送所有有对应的远程分支的本地分支。Git 2.0 版本之前,默认采用 matching 方法,现在改为默认采用 simple 方式。

参考文档