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 查看所有操作记录(用于恢复误删提交或分支)。
相关推荐
牧野星辰5 小时前
.gitignore文件的规范
git·github
二个半engineer11 小时前
GitLab Web 界面创建分支后pathspec ... did not match any file(s)
git·gitlab
尽兴-12 小时前
Git 清理指南:如何从版本库中移除误提交的文件(保留本地文件)
大数据·git·gitee·gitlab
飞翔的猪猪1 天前
GitHub Recovery Codes - 用于 GitHub Two-factor authentication (2FA) 凭据丢失时登录账号
前端·git·github
顾三殇1 天前
【编译工具】(版本控制)Git + GitHub Actions:自动化工作流如何让我的开发效率提升200%?
git·自动化·github
绅士玖1 天前
理解 .env 文件和 .gitignore 文件的作用与最佳实践
前端·git·代码规范
不爱学英文的码字机器1 天前
[Git] 标签管理
大数据·git·elasticsearch
不爱学英文的码字机器2 天前
[Git] 配置 Git
git
小慧10242 天前
1.2 git使用
git
m0_635647482 天前
git管理github上的repository(二)
git·github