Skip to content

Git 常用命令速查

Git 是目前世界上最先进的分布式版本控制系统。以下是日常开发中最高频使用的命令清单。

版本控制

1. 初始化与配置

命令说明
git init在当前目录初始化一个新的 Git 仓库
git clone <url>克隆远程仓库到本地
git config --global user.name "Your Name"设置提交时的用户名
git config --global user.email "email@example.com"设置提交时的邮箱
git config --list查看当前配置信息

2. 代码提交 (工作区 -> 暂存区 -> 本地仓库)

bash
# 查看文件状态
git status

# 添加指定文件到暂存区
git add <filename>

# 添加所有修改到暂存区
git add .

# 提交暂存区到本地仓库
git commit -m "提交说明信息"

# 修改最后一次提交的说明(或追加漏掉的文件)
git commit --amend

3. 分支管理

分支是 Git 的杀手级功能,用于并行开发。

命令说明
git branch列出本地所有分支
git branch <name>创建新分支
git checkout <name>切换到指定分支
git switch <name>(新版) 切换分支
git checkout -b <name>创建并切换到新分支
git merge <name>合并指定分支到当前分支
git branch -d <name>删除分支

4. 远程同步

bash
# 查看远程仓库地址
git remote -v

# 添加远程仓库
git remote add origin <url>

# 拉取远程代码并合并 (pull = fetch + merge)
git pull origin <branch_name>

# 推送本地代码到远程
git push origin <branch_name>

# 强制推送 (慎用,尤其在多人协作时)
git push -f origin <branch_name>

5. 撤销与回退

  • 丢弃工作区的修改 (未 add):

    bash
    git checkout -- <filename>
    # 或者新版命令
    git restore <filename>
  • 撤销暂存区的修改 (已 add, 未 commit):

    bash
    git reset HEAD <filename>
    # 或者新版命令
    git restore --staged <filename>
  • 版本回退 (已 commit):

    bash
    # 查看提交日志
    git log --oneline
    
    # 回退到上一个版本
    git reset --hard HEAD^
    
    # 回退到指定 commit_id
    git reset --hard <commit_id>

6. 其他实用技巧

  • 暂存工作现场 (临时去修 Bug):
    bash
    git stash       # 保存当前进度
    git stash pop   # 恢复进度
  • 查看差异:
    bash
    git diff        # 工作区 vs 暂存区
    git diff HEAD   # 工作区 vs 最新提交