本文最后更新于 2026年4月7日 凌晨
git 入门教程
git 是版本控制软件。
版本控制概念
版本控制是什么,为什么需要版本控制?
版本指若干文件内容所构成的整体,而控制指记录个整体以及变化。
举个例子:
当你再写一篇文章,写完之后就保存到电脑里面了。过了很久之后,再次打开发现措辞不当,进行了若干处修改。然后又过去一段时间,觉得上一次考虑不周,也许还是第一次的更好,此时你无比希望回到第一版。
而版本控制就是为了实现这样的目的:即可以保存任意状态下的文件内容,并且可以给出任意两种状态下差异。
有了版本控制,你就可以随心所欲的创作,和修改。不用担心记不住的问题,版本控制可以帮你想要保存的任何状态,你可以回到任意的状态中。简而言之,在版本控制中,你可以任意拨弄“时间线”,回到“过去”,从“过去”穿越到“未来”。
那么版本控制就是指 git 吗?
答案是否定的,git 是版本控制软件,但版本控制软件并不仅仅有 git。
git 基础配置
1 2 3 4 5
| git config --global user.name "name" git config --global user.email "name@xxx.com" git config --global core.editor vim [gui] encoding = utf-8
|
创建仓库:git init 拉取远程到本地:git clone 添加文件:git add
[filename] 添加所有文件:git add . 忽略文件:.gitignore
提交到本地仓库:git commite -m “commit message” 查看状态:git status
对比工具:git diff (使用 bc 代替)
配置全局邮箱与用户名
1 2 3 4
| git config --global user.name "zhang.san" git config --global user.email "zhang.san@xxx.com" git config --globa color.ui true git config --global init.defaultBranch main
|
配置文件说明
| 类型 |
优先级 |
路径 |
| 仓库路径 |
高 |
.git\config |
| 用户级别路径 |
中 |
C:\Users\<user-name>\.gitconfig |
| 系统级别路径 |
低 |
C:\Program Files\Git\etc\config |
配置文件命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| [user] name = name email = name@xxx.com [color] ui = true [alias] br = branch ci = commit co = checkout type = cat-file -t dump = cat-file -p st = status unstage= reset HEAD -- last = log -1 HEAD visual = !gitk hist = log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short
|
常用命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| git add file_name git commit -m "some comment" git status git cnfig --list git clone [url] git push origin HEAD:refs/for/master
git log --pretty=format:"%h - %an, %ar : %s" --graph git log --since=2.weeks git push [remote-name] [branch-name] git config --global alias.ci commit git config --global alias.last 'log -1 HEAD' git checkout -b branch_name git branch branch_name git checkout branch_name
git checkout -b hotfix
git add . git commit -m "做了一些修复工作" git checkout master git merge hotfix git branch -d hotfix //master 移动到 hotfix 后,hotfix 就要删除掉 git branch -f main HEAD~3 git cherry-pick <提交号> git rebase --interactive //拉取远程仓库并合并到本地,然后上传 git pull --rebase git push
git reflog git tag tage_name hash_id
|
1 2 3 4 5
| git clone --recursive [address]
git submodule init git submodule update
|
git 备忘录
git 多账户配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| ssh-keygen -t rsa -C 'yourEmail@xx.com' -f ~/.ssh/gitlab-rsa
ssh-keygen -t rsa -C 'yourEmail2@xx.com' -f ~/.ssh/github-rsa
Host gitlab.com HostName gitlab.com PreferredAuthentications publickey IdentityFile ~/.ssh/gitlab_id-rsa
Host github.com HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/github_id-rsa
|
相关资源链接
常见问题
Q: 带模块的仓库,下载出错如何继续?
A: 进入仓库,执行=git submodule update --init --recursive=,或者执行=git fetch [url]=
A: 使用 hash 切换分支 git checkout <hash>
Q: 跳过检验,直接提前.
A: git commit --no-verify -m "aaa"