文先生的博客 求职,坐标深圳。(wenfh2020@126.com)

Git 常用命令场景

2019-03-22

Git 是一个开源的分布式版本控制系统,在此记录自己常用的场景和命令。


1. 常用命令

查看 git 使用文档: "git --help""man git"

命令 描述
clone 拉取源码
git clone https://github.com/enki/libev.git
pull 拉取文件
push 提交文件
git push -u origin master
log 查看日志
git log –pretty=oneline
status 目录文件状态
git status .
checkout 检索文件或分支
git checkout sync_pic.sh
remote 查看 git 项目路径
git remote -v
reset 当前版本回退到指定历史版本
git reset –hard 2b050c8
show 查看提交版本的修改内容
git show 2b050c8
mv 重命名文件或文件名。
clean 清除没有提交的文件,参考《git clean 的用法》。
archive 类似 svn export 命令:git archive master | gzip > project.tgz

2. 场景

2.1. 创建项目流程

参考 github 创建一个新的项目。

  • create a new repository on the command line.
1
2
3
4
5
6
echo "# xxxxx" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/wenfh2020/xxxxx.git
git push -u origin master
  • push an existing repository from the command line.
1
2
git remote add origin https://github.com/wenfh2020/xxxxx.git
git push -u origin master

2.2. 回退

git 回退到之前的提交版本,可以使用命令 reset,这个方法比较简单,也比较暴力。

  • 查看要回退的版本 commmit id, 使用命令:(git log) / (git log –pretty=oneline) / (git reflog)
1
2
3
4
5
6
5b8f126075fbd686b5a2c810ea2a4d918e0770d2 (HEAD -> master, origin/master, origin/HEAD) update obj
2b050c8547f3d92a014a3d24669bc1b61e89a5ea update blog
80c72441eef04e945a091c6f1891761d332ca91a update blog
b5b7a47e99a354cc5788185d0e0e767e8eda9677 update blog
212edc157ade1d3eb7b89c14e5032b3254ab56ac rm file
68309ca340b8cf65921fc7019770d100999c5f54 rdb application & struct
  • 回退到指定版本。
1
git reset --hard 2b050c8547f3d92a014a3d24669bc1b61e89a5ea
  • 回退到上一个版本。
1
git reset --hard HEAD^
  • 回退到前 N 次提交的版本。
1
git reset --hard HEAD~N
  • 强制提交到远程。
1
git push -u origin head --force

2.3. 创建分支

参考 Git-创建分支流程


2.4. 恢复 git rm 误删文件

1
2
3
git rm -f 2020-02-20-14-22-08.png
git reset HEAD 2020-02-20-14-22-08.png
git checkout 2020-02-20-14-09-19.png   

3. gitignore

可以通过设置 .gitignore 文件,忽略提交指定文件,这样可以提交 git 操作效率。下面命令,先忽略全部,再把指定的关注的文件类型添加进去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
*
!*/
!*.json
!*.sh
!*.h
!*.hpp
!*.cpp
!*.md
!*.c
!*.proto
!*.cc
!*.txt

.vscode
*.pb.cc
*.pb.h

4. 修改仓库路径

1
2
3
4
# 查看仓库远程路径。
git remote -v

git remote set-url origin <new url>

5. github 加速

访问 github 源码慢,可以通过 github 加速,获取对应的链接然后 clone 对应的项目仓库源码。

  • 浏览器搜索添加 github加速 扩展程序。
  • 获取对应项目仓库的加速链接。

6. 参考


作者公众号
微信公众号,干货持续更新~