Git 常用命令

首次发布:2025-12-01

1. 基础配置与初始化

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

# 查看配置信息
git config --list

# 初始化一个新的 Git 仓库
git init

# 克隆远程仓库到本地
git clone <repository_url>

2. 日常工作流操作

# 查看工作区状态
git status

# 将文件添加到暂存区
git add <file_name>       # 添加指定文件
git add .                 # 添加所有修改的文件

# 提交暂存区的文件到本地仓库
git commit -m "Commit message"
git commit -am "Commit message"  # 跳过暂存区,直接提交已跟踪的文件

# 查看提交历史
git log                   # 查看详细提交日志
git log --oneline         # 简洁格式显示日志
git log --graph           # 图形化显示分支合并历史

3. 分支管理

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

# 创建分支
git branch <branch_name>

# 切换分支
git checkout <branch_name>
git switch <branch_name>  # Git 2.23+ 推荐用法

# 创建并切换到新分支
git checkout -b <branch_name>
git switch -c <branch_name>

# 合并分支(先切换到目标分支)
git merge <source_branch>

# 删除分支
git branch -d <branch_name>   # 删除已合并的分支
git branch -D <branch_name>   # 强制删除分支

4. 远程仓库操作

# 查看远程仓库信息
git remote -v

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

# 修改远程仓库的 URL
git remote set-url origin <new_repository_url>

# 拉取远程仓库更新
git pull origin <branch_name>

# 推送本地分支到远程仓库
git push origin <branch_name>

# 推送并设置上游分支(首次推送)
git push -u origin <branch_name>

5. 撤销与回退

# 撤销工作区的修改
git checkout -- <file_name>

# 撤销暂存区的修改(放回工作区)
git reset HEAD <file_name>

# 回退到历史版本(保留修改)
git reset --soft <commit_id>

# 彻底回退到历史版本(删除后续提交)
git reset --hard <commit_id>

# 放弃本地所有修改,回到最近一次提交状态
git restore .

6. 暂存操作

# 暂存当前工作区的修改
git stash

# 查看暂存列表
git stash list

# 恢复最近一次暂存的内容
git stash pop

# 应用指定暂存(不删除暂存记录)
git stash apply stash@{0}

# 删除暂存记录
git stash drop stash@{0}

本文来自 www.luofenming.com