最近复习了一下git,总结了一下命令行的基本使用:
0. 基本理论
a. 基本概念
Working Directory: 就是平时存放项目代码的地方
Stage(Index): 用于临时存放改动,事实上他只是一个文件,保存即将提交的文件列表信息
Repository: 就是安全存放数据的位置,这里边有你所提交的所有版本的数据,其中HEAD指向最新放入仓库的版本
b. 一般工作流程
1. 在工作目录中添加,修改文件.
2. 将需要进行版本管理的文件放入暂存区域(add)
3. 将暂存区域的文件提交到Git仓库(commit)
1. 基础实战
a. git前置配置:
git config --global user.name "Rush"
git config --global user.email "xxx@xxx.com"
b. 初始化git仓库
在对应的项目工程文件夹下终端命令 **git init
**初始化仓库
c. git常用命令介绍
# 将某个文件添加到stage区域
git add "filename"
# 全部添加
git add *
# 将暂存区的改动全部添加到repo中,并附加说明"第一次提交"
git commit -m "第一次提交"
# 版本状态查询
git status
# 从repo恢复暂存区域(用repo的文件覆盖暂存区)
git reset HEAD
# 使用git checkout -- <file> 将暂存区文件检出到working directory
# 此处等于用暂存区的文件覆盖工作区文件
git checkout -- test.txt
#将文件直接添加到stage并提交
git commit -am "what you have done"
# git add 命令用于吧工作目录的文件放入暂存渔区
# git commit 命令用于把暂存区域的文件提交到Git仓库
# git reset 命令用于把Git仓库的文件还原到暂存区域(有三种模式)
# git checkout 用于把暂存区的文件还原到工作目录
2. 高级操作
a. 回滚快照
# HEAD标识最新提交快照的位置(31f46be),而HEAD~表示上一个快照(d19e3ff),HEAD~~表示前两个快照位置..
# git reset 快照id
git reset HEAD~
git reset 的三种模式:
- –soft 单单移动HEAD的指向
- –mixed [默认] 将快照回滚到stage
- –hard 将stage区域还原到工作目录
# 回滚指定快照
git reset 00c2929
# 回滚个别文件,他会忽略移动HEAD指向这一步,直接将指定快照的指定文件回滚到暂存区域
git reset 快照 文件名/路径
# 向前滚,(需要知道前面的快照ID)
git reset 快照
# git log 来查看提交版本(显示到HEAD指针指向的版本截至)
# git reflog 来查看所有的历史版本(可用于前滚)(重要)
b. git diff 操作
c. 修改最后一次提交(本地)
两种场景:
- 版本刚提交到仓库,想起还有文件没有add进来
- 版本刚提交到仓库,想起说明写的不够全面,想修改说明
git commit --amend -m "新的提交说明"
d. 删除文件
# 删除working directory 和stage中的文件
git rm <filename>
e. 重命名
# 使用git来重命名能保持文件的跟踪关系(直接改名会导致文件无法追踪)
git mv old new
f. 使用.gitignore
忽略某些文件
vim .gitignore
.idea # 忽略.idea文件夹
.gitignore # 忽略 .gitignore 本身
3. 分支操作
这里只作简单记录
git branch feature # 从当前快照创建feature分支
git checkout feature # 切换到feature 分支
git commit -m "commit on feature"
git checkout master
# add sth...
git commit -m "commit on master"
git log --decorate --all --oneline --graph
git merge feature # 合并分支 feature
# 可能需要解决冲突
# 删除分支
git branch -d feature
# 匿名分支
git checkout HEAD~
4. 远程操作
# 添加远程仓库 git remote add <name> url
git remote add original xxxxxx
#将本地的master推送到远程的orignal上,-u指定上游
git push -u original master
# git pull == git fetch + git merge (或者 git rebase)
git fetch origin
git merge origin/master
# 或者
git pull original
# 查看设置的远程仓库
git remote -v
git remote
# 删除远程仓库记录(对实际的远程仓库没影响
git remote rm <name>