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 查看所有操作记录(用于恢复误删提交或分支)。
相关推荐
唐青枫2 小时前
Git 提交时神秘的 create mode 100644 到底是什么?一文告诉你答案!
git
春生野草2 小时前
Git-git stash与分支管理
git
ljh5746491192 小时前
Git合并冲突解决方法
git
悟能不能悟2 小时前
git revert commit和undo commit的区别
git
222you14 小时前
Git的diff命令
git
补三补四16 小时前
Git 基础操作指南
大数据·git·elasticsearch
222you1 天前
git的命令
git
Coolbike1 天前
Git工作流
git
~央千澈~1 天前
实战针对本地项目git如何移除旧仓库关联并且添加关联新仓库-优雅草卓伊凡
git
JH30731 天前
git常用命令大全
git