Git 常用命令速查

日常开发 Git 操作速查手册,持续更新。

1、克隆

git clone <远程仓库地址>

2、切换分支

git checkout <分支名>

3、数据拉取到本地仓库(不自动合并)

git fetch

4、拉取到本地仓库并自动合并

git pull

5、合并

git merge <分支名>

6、查看分支

git branch

7、查看远程所有分支

git branch -r

8、查看本地和远程的所有分支

git branch -a

9、新建分支

git branch develop

10、从当前分支拷贝并切换到新分支

git checkout -b develop

11、将本地新的分支推送至远程

git push origin develop

12、暂存

git stash

13、恢复暂存区

git stash pop

14、删除本地分支

git branch -d <分支名字>

15、删除远程分支

git push origin --delete <分支名字>

16、查看远程仓库详情(含远程已删除的分支信息)

git remote show origin

17、清理远程已删除的本地追踪分支(强制删除)

git remote prune origin

18、查看代码修改状态

git status

19、提交到暂存区

git add <file>

20、提交暂存区文件

git commit -m "提交说明"

21、分支推送到远程

git push
# 或指定分支
git push origin <本地分支名>

22、合并代码

(1)先切换到要合并到的目标分支

git checkout <目标分支名>

(2)合并源分支(--no-ff 保留分支历史)

git merge --no-ff <源分支名>

(3)合并完成推送远程

git push

23、重新同步原分支

git rebase <分支名>

24、rebase 同步场景

场景:从 develop 拉取了 feature-200 分支,开发完想合并回 develop 时,发现 develop 已被别人提交了新代码。

(1)切换到 develop 分支

git checkout develop

(2)同步 develop 分支最新代码

git pull

(3)切换回 feature-200 分支

git checkout feature-200

(4)重新同步 develop

git rebase develop

(5)强制推送

git push -f
⚠️ 注意:-f 强制推送会覆盖远程历史,仅在自己负责的分支上使用。

25、查看 / 更换用户名邮箱

(1)查看当前的

git config user.name
git config user.email

(2)查看全局的

git config --global user.name
git config --global user.email

(3)更换局部的

git config user.name "<name>"
git config user.email "<email>"

(4)更换全局的

git config --global user.name "<name>"
git config --global user.email "<email>"

(5)使用已有的凭证

git config credential.helper store
在 Jenkins 中 shell 脚本用 git tag 新建标签推送至远程时有用。

26、查看远程仓库地址

git remote -v

27、创建 git 仓库

mkdir <directory>
cd <directory>
git init
touch a.txt
git add a.txt
git commit -m "first commit"
git remote add origin <远程服务器地址>.git
git push -u origin master

28、合并多个 commit(squash)

场景:从 develop 拉取了 feature-100 分支并提交了 2 个 commit,合并回 develop 前,为便于审核查阅,将 2 个 commit 合并为 1 个。

(1)交互式 rebase,合并最近 N 个提交

git rebase -i HEAD~<提交节点数量>

(2)多次操作导致本地与远程分支不一致时,强制推送

git push -f

标签: none

添加新评论