太久没写代码了 git命令都有些乱了 此贴记录一下:

直接贴ai搜出来的结果,后面懒得搜了,查这个文章回忆了

1. 初始化与配置

# 全局配置用户信息(首次使用必配)
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

# 初始化本地仓库
git init

# 克隆远程仓库
git clone <repository_url>
git clone -b <branch_name> <repository_url>  # 克隆指定分支

2. 日常提交流程

# 查看工作区状态
git status
git status -s  # 简洁模式

# 添加文件到暂存区
git add <file_name>       # 添加指定文件
git add.                 # 添加所有变更文件

# 提交到本地仓库
git commit -m "feat: 添加新功能描述"

# 跳过暂存直接提交已跟踪文件的修改
git commit -am "fix: 修复bug"

3. 分支管理

# 查看分支
git branch          # 本地分支
git branch -r       # 远程分支
git branch -a       # 所有分支

# 创建与切换
git branch <new_branch>            # 创建新分支
git checkout <branch_name>         # 切换分支
git checkout -b <new_branch>       # 创建并切换(常用)
git switch <branch_name>           # Git 2.23+ 推荐切换命令
git switch -c <new_branch>         # Git 2.23+ 推荐创建并切换

# 合并分支
git merge <branch_name>            # 合并指定分支到当前分支

# 删除分支
git branch -d <branch_name>        # 删除已合并的本地分支
git branch -D <branch_name>        # 强制删除未合并的本地分支
git push origin --delete <branch_name> # 删除远程分支

4. 远程同步

# 关联远程仓库
git remote add origin <repository_url>
git remote -v  # 查看远程地址

# 拉取代码
git pull origin <branch_name>      # 拉取并合并
git pull --rebase origin <branch_name> # 拉取并变基(保持历史线性,推荐)

# 推送代码
git push origin <branch_name>      # 推送到远程
git push -u origin <branch_name>   # 首次推送并建立跟踪关系
git push --force-with-lease        # 安全强制推送(覆盖远程历史前检查)

5. 查看与对比

# 查看提交历史
git log
git log --oneline                  # 单行显示
git log --graph --oneline --all    # 图形化显示所有分支
git log -n 5                       # 最近5条记录
git log --author="Name"            # 按作者筛选

# 查看差异
git diff                           # 工作区与暂存区差异
git diff --cached                  # 暂存区与HEAD差异
git diff <commit1> <commit2>       # 两个提交之间的差异

# 查看具体提交详情
git show <commit_id>

6. 撤销与回退

# 撤销工作区修改(未add)
git restore <file_name>            # Git 2.23+ 推荐
# git checkout -- <file_name>     # 旧版命令

# 取消暂存(已add未commit)
git restore --staged <file_name>   # Git 2.23+ 推荐
# git reset HEAD <file_name>      # 旧版命令

# 版本回退(已commit)
git reset --soft <commit_id>       # 回退提交,保留暂存区和工作区
git reset --mixed <commit_id>      # 回退提交和暂存区,保留工作区(默认)
git reset --hard <commit_id>       # 彻底回退,丢弃所有变更(危险)

# 撤销已推送的提交(生成新提交,安全)
git revert <commit_id>

7. 临时保存与清理

# 暂存当前工作进度
git stash                          # 保存现场
git stash save "message"           # 带说明保存
git stash list                     # 查看列表
git stash pop                      # 恢复并删除最新stash
git stash apply stash@{0}          # 恢复指定stash但不删除

# 清理未跟踪文件
git clean -fd                      # 删除未跟踪的文件和目录(危险,先试用 -n 预览)

8. 标签管理

# 查看标签
git tag

# 创建标签
git tag v1.0.0                     # 轻量标签
git tag -a v1.0.0 -m "版本说明"    # 附注标签

# 推送标签
git push origin v1.0.0             # 推送单个标签
git push origin --tags             # 推送所有本地标签