前言

转载自git 宝典并 md 重新编辑

建立本地仓库

命令 说明
git init 创建本地仓库
git init [project-name] 创建指定名称的本地仓库
git remote add origin git@github.com:UserName/yourProjectName.git 将本地仓库和远程仓库关联起来,避免每次 push 时都需要指定远程地址
git clone https://github.com/zhoulujun/yourProjectName.git 克隆远程仓库到本地

提交修改

命令 说明
git add [file1] [file2] ... 将指定文件添加到暂存区
git add [dir] 将指定目录添加到暂存区
git add -A 添加当前目录的所有文件到暂存区
git add -p 逐个确认每个变化的提交,适用于同一个文件的多处变化
git rm xxx 从本地仓库中删除指定文件
git rm -r xxx 从本地仓库中删除指定文件夹
git rm --cached [file] 从暂存区中删除文件,但保留工作目录中的文件
git mv [file-original] [file-renamed] 改名文件并将其改名操作放入暂存区
git commit -m "注释" 提交本机缓存中的内容到本机的 HEAD 中
git commit -a 提交工作区自上次 commit 之后的变化,直接到仓库区
git commit -v 提交时显示所有 diff 信息
git commit --amend -m [message] 替代上一次提交,用新的 commit 来修正提交信息
git commit --amend [file1] [file2] ... 重做上一次 commit 并包括指定文件的新变化
git push origin master 将本地的 commit 推送到远程服务器上
git push remoteBranchName tagName 提交指定 tag
git push remoteBranchName --tags 提交所有 tag

查看状态

命令 说明
git status 查看当前状态
git branch 查看本地所有分支
git branch -r 查看远程所有分支
git branch -a 查看本地和远程所有分支
git tag 列出所有 tag
git show tagName 查看 tag 信息
git log --stat 显示 commit 历史,以及每次 commit 发生变更的文件

分支操作

命令 说明
git checkout branchName 切换到指定分支,并更新工作区
git merge branchName 合并指定分支到当前分支
git branch newBranchName 新建一个分支,但依然停留在当前分支
git branch --track branch remote-branch 新建一个分支,并与指定的远程分支建立追踪关系
git branch -D branchName 删除目标分支
git checkout -b branchName 新建并切换至新分支
git branch -d -r branchName 删除远程分支
git branch -m oldbranchname newbranchname 重命名分支,使用 -M 参数则表示强制重命名

重命名远程分支

命令 说明
git branch -m old_name new_name 重命名分支(本地)
git checkout -b new_branch_name from_branch_name 本地建立新分支并切换过去
git push origin --delete old_name 删除远程分支
git push origin :old_branch 删除旧分支
git push --set-upstream origin new_branch 推送新分支,并设置本地分支跟踪新的远程分支

分支与主干合并

命令 说明
git merge branch --squash 在主干上合并分支,并提交合并后的代码
git commit -m '合并备注' 提交合并后的代码
git push 将代码推送到远程仓库
git merge master --squash 在分支上合并主干代码,并提交合并后的代码
git commit -m '合并备注' 提交合并后的代码
git push 将代码推送到远程仓库

强制覆盖本地代码

命令 说明
git fetch --all 与远程仓库保持一致
git reset --hard origin/master 强制覆盖本地代码
git pull 更新本地仓库
git fetch --all && git reset --hard origin/master && git pull 单条执行的强制覆盖本地命令

修改远程仓库地址

命令 说明
git remote origin set-url [url] 修改远程仓库地址
git remote rm origin 删除现有的远程仓库地址
git remote add origin [url] 添加新的远程仓库地址
直接修改 .git/config 文件 编辑 .git/config 文件中的项目地址

Git 配置

命令 说明
git config --list 查看配置列表
git config --global user.name "xxx" 配置用户名
git config --global user.email "xxx" 配置邮箱
ssh-keygen -t rsa -C "Github 的注册邮箱" 创建本地 SSH 密钥
在 GitHub 中添加 SSH key 将生成的 SSH key 添加到 GitHub 帐号中
ssh -T git@github.com 验证 SSH 配置成功

.gitignore 配置

命令 说明
在本地仓库根目录创建 .gitignore 文件 用于忽略指定文件和文件夹
[Tt]emp/ 过滤 Temp\temp 文件夹
*.suo 过滤 .suo 文件
!*.c 不过滤 .c 文件

这些表格可以帮助你更清晰地了解和记忆 Git 操作命令。

引用于 git 宝典—应付日常工作使用足够的指北手册 - git 使用的的一些日常小结合集 - 周陆军的个人网站 (zhoulujun.cn)