Skip to content

基础操作

bash
# 初始化仓库
git init                    # 在当前目录创建新仓库
git clone <URL>             # 克隆远程仓库到本地

# 查看状态
git status                  # 查看文件状态(未跟踪、修改、暂存)
git diff                    # 查看工作区与暂存区的差异
git diff --staged           # 查看暂存区与最新提交的差异

# 文件操作
git add <file>              # 将文件添加到暂存区
git add .                   # 添加所有文件
git reset <file>            # 从暂存区移除文件
git checkout -- <file>      # 丢弃工作区的修改
git rm <file>               # 删除文件并记录到暂存区
git mv <old> <new>          # 重命名文件并记录到暂存区

# 提交
git commit -m "描述"        # 提交暂存区的变更
git commit -am "描述"       # 跳过暂存区,直接提交已跟踪文件的修改
git commit --amend          # 修改最近一次提交

分支管理

bash
git branch                  # 列出本地分支
git branch -r               # 列出远程分支
git branch -a               # 列出所有分支
git branch <name>           # 创建新分支
git checkout <name>         # 切换到指定分支
git checkout -b <name>      # 创建并切换到新分支
git branch -d <name>        # 删除分支(需先合并)
git branch -D <name>        # 强制删除分支
git merge <branch>          # 合并指定分支到当前分支
git rebase <branch>         # 将当前分支的变更应用到指定分支上

远程仓库

bash
git remote                  # 列出远程仓库
git remote -v               # 详细列出远程仓库
git remote add <name> <url> # 添加远程仓库
git fetch <remote>          # 获取远程仓库的变更
git pull <remote> <branch>  # 获取并合并远程分支
git push <remote> <branch>  # 推送本地分支到远程仓库
git push -u <remote> <branch> # 推送并关联上游分支
git push <remote> --delete <branch> # 删除远程分支

历史记录

bash
git log                     # 查看提交历史
git log --oneline           # 单行显示历史
git log --graph             # 图形化显示分支合并历史
git log -p <file>           # 查看文件的修改历史
git show <commit>           # 查看特定提交的详情
git blame <file>            # 查看每行代码的最后修改者

撤销与回滚

bash
git revert <commit>         # 创建一个新提交,撤销指定提交的变更
git reset <commit>          # 重置当前分支到指定提交
git reset --hard <commit>   # 彻底丢弃指定提交之后的所有变更
git checkout <commit>       # 查看历史版本(HEAD 变为 detached 状态)

标签(Tag)

bash
git tag                     # 列出所有标签
git tag <name>              # 创建轻量标签
git tag -a <name> -m "描述" # 创建附注标签
git tag -d <name>           # 删除标签
git push <remote> <tag>     # 推送标签到远程仓库
git push <remote> --tags    # 推送所有标签

暂存(Stash)

bash
git stash                   # 暂存当前未提交的修改
git stash list              # 查看暂存列表
git stash apply             # 恢复最近一次暂存
git stash pop               # 恢复并删除最近一次暂存
git stash drop              # 删除最近一次暂存
git stash clear             # 删除所有暂存