git常用命令

1. 仓库初始化与克隆

复制代码
git init 初始化当前目录为 Git 仓库。
git clone <repo-url> 克隆远程仓库到本地。

2. 基本操作

复制代码
git add <file> 将文件添加到暂存区(git add . 添加所有修改)。
git commit -m "提交说明" 提交暂存区的改动到本地仓库。
git status 查看工作区和暂存区的状态。
git log 查看提交历史(--oneline 显示简略信息,-p 查看差异)。
git diff 查看未暂存的改动(git diff --staged 查看已暂存的改动)。

3. 分支管理

复制代码
git branch 列出所有本地分支(-a 包含远程分支)。
git branch <branch-name> 创建新分支。
git checkout <branch-name> 切换到指定分支(或 git switch <branch-name>)。
git merge <branch-name> 将指定分支合并到当前分支。
git rebase <branch-name> 变基操作,将当前分支的提交移到目标分支顶端。
git branch -d <branch-name> 删除本地分支(-D 强制删除未合并的分支)。

git push origin --delete <branch_name>  只删除远程分支

本地与远程同步删除‌:  
先删除本地分支(git branch -d <branch_name>),
再推送删除到远程(git push origin <branch_name>)

git branch -m old-branch new-branch  重命名本地分支

重命名远程分支步骤:
git branch -m old-branch new-branch  重命名本地分支
git push origin new-branch  推送到远程
git push origin --delete old-branch  删除旧的远程分支

4. 远程仓库

复制代码
git remote -v 查看关联的远程仓库地址。
git remote add <name> <repo-url> 添加远程仓库(如 origin)。
git push <remote> <branch> 推送本地提交到远程仓库(-u 首次推送时关联分支)。
git pull <remote> <branch> 拉取远程分支并合并到当前分支(等价于 git fetch + git merge)。
git fetch <remote> 下载远程仓库的更新,但不自动合并。

5. 撤销与回退

复制代码
git restore <file> 撤销工作区的修改(等同于 git checkout -- <file>)。
git restore --staged <file> 将文件从暂存区移回工作区(等同于 git reset HEAD <file>)。
git reset <commit-hash> 回退到指定提交(--soft 保留修改,--hard 丢弃修改)。
git revert <commit-hash> 创建一个新提交来撤销指定提交的改动。

6. 标签管理

复制代码
git tag 列出所有标签。
git tag <tag-name> 创建轻量标签(-a 创建附注标签,-m "备注" 添加信息)。
git push <remote> --tags 推送所有标签到远程仓库。

7.贮藏修改

复制代码
git stash 临时保存工作区和暂存区的修改,默认不会保存未跟踪的文件(新创建且未 git add 的文件)。
git stash save "备注信息"    储藏并添加描述
git stash list 查看所有储藏的列表(格式:stash@{0}: 备注)
git stash pop [stash@{n}]  恢复指定储藏(默认为最新 stash@{0}),并删除该储藏。
git stash apply [stash@{n}] 恢复指定储藏,但不删除储藏记录(可多次应用同一储藏)
git stash drop [stash@{n}]  删除指定储藏(默认删除最新 stash@{0})
git stash clear  删除所有储藏记录(谨慎使用,不可恢复!)。
git stash show stash@{n}   查看储藏的简略文件改动(默认显示最新储藏)。
git stash show -p stash@{n}  查看储藏的详细代码差异(类似 git diff)。
git checkout stash@{n} -- <file-path>  从储藏中恢复单个文件

git stash branch <new-branch-name> stash@{n}  新建一个分支,并恢复指定储藏(适用于储藏内容与当前分支冲突时)。

误删储藏后恢复:
通过 git reflog 查找 stash 操作的哈希值,再用 git stash apply <hash> 恢复(需 Git 2.37+)。

8. 其他实用命令

复制代码
git cherry-pick <commit-hash> 将指定提交应用到当前分支。
git reflog 查看所有操作记录(用于恢复误删提交或分支)。
相关推荐
泰勒朗斯7 小时前
如何在新机器上设置github完成内容git push
git·github
小妖66612 小时前
git branch -a 还有一些已经删除了的分支
git
&Sinnt&1 天前
Git 版本控制完全指南:从入门到精通
git·后端
Tiny2141 天前
多人协同开发时Git使用命令
git
WebGirl1 天前
代码Revert后再次Merge会丢失的问题
git
小皮侠2 天前
nginx的使用
java·运维·服务器·前端·git·nginx·github
HalukiSan2 天前
如何提交PR
git·gitlab·github
爱莉希雅&&&2 天前
shell编程之awk命令详解
linux·服务器·git
baiyu332 天前
成为git砖家(12): 看懂git合并分支时冲突提示符
git
wu_aceo2 天前
将本地项目提交到Gitee
git·gitee·提交·本地提交·上传git