文章目录
一、创建版本库
- 创建文件夹
git mkdir <FolderName>
- 显示当前目录
pwd
- 创建仓库
git init
- 显示隐藏目录
ls -ah
- 添加文件到本地版本库
git add <FileName>
- 提交文件到本地版本库
git commit -m "<Message>"
二、版本管理
1. 查看版本状态
- 查看仓库当前状态
git status
- 查看文件修改内容
git diff <FileName>
注意:
git diff
是查看工作区与暂存区的差别;
git diff --cached
是查看暂存区与本地仓库的差别;
git diff HEAD
是查看工作区与本地仓库的差别,其中HEAD代表的是最近的一次commit的信息;
git diff <CommitId> <CommitId>
是查看版本库和版本库的差别。
2. 版本回退
- 查看从最近到最远的提交日志
git log
- 简化输出提交日志
git log --pretty=oneline
- 版本回退
git reset --hard <CommitId>
注:<CommitId>
可换成HEAD^
、HEAD^^
、HEAD~100
,分别表示回退到上一版本、上上版本和往上100个版本。 - 查看文件内容
cat <FileName>
- 查看记录的每一次输入命令
git reflog
3. 撤销修改
- 丢弃对工作区的修改
git checkout -- <FileName>
注: 分两种情况,一种是<FileName>
自修改后还没有放到暂存区,撤销修改时就回到和版本库一模一样的状态;另一种是<FileName>
已经添加到暂存区后,撤销修改时就回到和添加到暂存区时一模一样的状态。总之,就是让这个文件回到最近一次git commit
或git add
时的状态。 - 撤销对暂存区的修改
git reset HEAD <FileName>
,把暂存区的修改撤销掉,重新放回工作区。 - 从暂存区恢复工作区
git resotre --worktree <FileName>
- 从 master 恢复暂存区
git resotre --staged <FileName>
- 从 master 同时恢复工作区和暂存区
git restore --source=HEAD --staged --worktree <FileName>
4. 删除文件
- 从版本库删除文件
git rm <FileName>
+git commit -m "<Message>"
三、远程仓库
- 本地关联远程仓库
git remote add <RemoteLibraryName> git@github.com:<YourGitHub>/<RepositoryName>.git
- 克隆远程仓库
git clone <ssh协议或者https协议>
- 抓取远程的新提交
git pull
- 本地库内容推送到远程
git push -u <RemoteLibraryName> <Branch>
,第一次推送时,加上-u
参数,Git 不但会把本地的<Branch>
分支内容推送到远程新的<Branch>
分支,还会把本地的<Branch>
分支和远程的<Branch>
分支关联起来,在以后的推送或者拉取时就可以简化命令。 - 查看远程库信息
git remove -v
- 删除远程库
git remote rm <RemoteLibraryName>
- 在本地创建和远程分支对应的分支
git checkout -b <BranchName> <RemoteLibraryName>/<BranchName>
- 建立本地分支和远程分支的关联 `git branch --set-upstream /
四、分支管理
1. 创建与合并分支
- 创建分支
git checkout -b <BranchName>
,或者git switch -c <BranchName>
-b
&-c
参数表示创建并切换,相当于以下两条命令:
git branch <BranchName>
git checkout <BranchName>
或者git switch <BranchName>
- 查看分支
git branch
- 切换分支
git checkout <BranchName>
,或者git switch <BranchName>
- 合并分支
git merge <BranchName>
- 删除分支
git branch -d <BranchName>
强制删除分支git branch -D <BranchName>
2. 解决冲突
- 查看冲突的文件
git status
- 手动解决冲突后
git add
和git commit
- 查看分支合并情况
git log --graph --pretty=oneline --abbrev-commit
3. 分支管理策略
- 在
Fast forward
模式下,删除分支后会丢掉分支信息,要避免此情况,在合并分支时要禁用Faster forward
模式,采用git merge --no-ff -m "<Message>" <BranchName>
4. Bug分支
- 存储当前工作现场
git stash
- 查看
stash
内容git stash list
- 恢复并删除
stash
内容git stash pop
相当于git stash apply
+git stash drop
- 复制提交的修改到其他分支,先切换到要修改的分支,然后
git cherry-pick <CommitId>
5. Rebase
- 把分叉的提交历史“整理”成一条直线
git rebase
五、标签管理
- 创建标签
git tag <TagName>
git tag -a <TagName> -m "<Message>" <CommitId>
,-a
指定标签名,-m
指定说明文字 - 查看所有标签
git tag
- 查看标签信息
git show <TagName>
- 推送一个本地标签到远程
git push <RemoteLibraryName> <TagName>
推送全部未推送过的本地标签git push <RemoteLibraryName> --tags
- 删除本地标签
git tag -d <TagName>
- 删除远程标签
git push <RemoteLibraryName> :refs/tags/<TagName>