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 查看所有操作记录(用于恢复误删提交或分支)。
相关推荐
xbd_zc2 小时前
【Git命令】
git
hqxstudying3 小时前
Git的使用
git
F_D_Z4 小时前
【清晰教程】查看和修改Git配置情况
git
漫谈网络5 小时前
保持本地 Git 项目副本与远程仓库完全同步
git
李天琦10 小时前
git查看commit属于那个tag
linux·git·云计算
Hoking14 小时前
CentOS7.9环境离线部署docker和docker-compose的两种方式
git·docker·容器
Clownseven14 小时前
用Git管理你的服务器配置文件与自动化脚本:版本控制、变更追溯、团队协作与安全回滚的运维之道
运维·服务器·git
F_D_Z15 小时前
【清晰教程】利用Git工具将本地项目push上传至GitHub仓库中
git·github
天天摸鱼的java工程师18 小时前
Git 分支管理规范:从理论到实战的企业级最佳实践
java·git·后端
深兰科技19 小时前
青岛市长任刚与深兰科技董事长陈海波会谈,深兰青岛项目即将进入快车道!
人工智能·git·docker·jupyter·深兰科技·青岛项目·陈海波