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 查看所有操作记录(用于恢复误删提交或分支)。
相关推荐
爱莉希雅&&&8 小时前
shell编程之awk命令详解
linux·服务器·git
baiyu338 小时前
成为git砖家(12): 看懂git合并分支时冲突提示符
git
wu_aceo12 小时前
将本地项目提交到Gitee
git·gitee·提交·本地提交·上传git
随便取个六字1 天前
GIT操作 学习
git·学习
星源~1 天前
tree 命令集成到 Git Bash:可视化目录结构的指南
git·单片机·物联网·嵌入式·项目开发
zhaqonianzhu1 天前
git gerrit安装钩子
git·gerrit
这是个栗子1 天前
【问题解决】VSCode终端中看不到Git-Bash
ide·git·vscode
悲伤小伞1 天前
linux_git的使用
linux·c语言·c++·git
天机️灵韵1 天前
云效DevOps vs Gitee vs 自建GitLab的技术选型
git·开源项目
荔枝吻2 天前
【AI总结】Git vs GitHub vs GitLab:深度解析三者联系与核心区别
人工智能·git·github