一文讲清 Git 基本常用命令

Git 从入门到精通命令总结

一、配置 Git

1
2
3
4
5
6
7
8
9
# 设置用户名和邮箱
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

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

# 配置默认编辑器
git config --global core.editor "vim"

二、创建和初始化仓库

1
2
3
4
5
# 初始化一个新的 Git 仓库
git init

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

三、基本操作

1. 添加文件到暂存区

1
2
3
4
5
# 添加单个文件
git add <file>

# 添加所有文件
git add .

2. 提交到本地仓库

1
2
3
4
5
# 提交暂存区的内容到仓库
git commit -m "Commit message"

# 提交并跳过暂存区(直接从工作区提交)
git commit -a -m "Commit message"

3. 查看状态与日志

1
2
3
4
5
6
7
8
# 查看当前仓库状态
git status

# 查看提交历史
git log

# 简化显示提交历史
git log --oneline

4. 比较修改

1
2
3
4
5
# 查看工作区和暂存区的差异
git diff

# 查看暂存区和最后一次提交的差异
git diff --cached

5. 删除与恢复文件

1
2
3
4
5
6
7
8
# 删除文件并提交
git rm <file>

# 恢复暂存区的文件到工作区
git restore <file>

# 取消暂存的文件
git restore --staged <file>

四、分支管理

1. 创建与切换分支

1
2
3
4
5
6
7
8
# 创建新分支
git branch <branch_name>

# 切换分支
git checkout <branch_name>

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

2. 查看分支

1
2
3
4
5
# 查看所有分支
git branch

# 查看远程分支
git branch -r

3. 合并分支

1
2
# 合并分支到当前分支
git merge <branch_name>

4. 删除分支

1
2
3
4
5
# 删除本地分支
git branch -d <branch_name>

# 强制删除本地分支
git branch -D <branch_name>

五、远程仓库

1. 管理远程仓库

1
2
3
4
5
6
7
8
# 查看当前远程仓库
git remote -v

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

# 删除远程仓库
git remote remove <name>

2. 拉取与推送

1
2
3
4
5
# 从远程仓库拉取代码
git pull <remote> <branch>

# 推送代码到远程仓库
git push <remote> <branch>

3. 克隆仓库

1
2
# 克隆远程仓库
git clone <repository_url>

六、标签管理

1. 创建标签

1
2
3
4
5
# 创建轻量标签
git tag <tag_name>

# 创建附注标签
git tag -a <tag_name> -m "Tag message"

2. 查看与删除标签

1
2
3
4
5
# 查看所有标签
git tag

# 删除标签
git tag -d <tag_name>

3. 推送标签到远程仓库

1
2
3
4
5
# 推送单个标签
git push <remote> <tag_name>

# 推送所有标签
git push <remote> --tags

七、高级操作

1. 暂存修改

1
2
3
4
5
6
7
8
9
10
11
# 保存当前工作进度
git stash

# 查看暂存列表
git stash list

# 恢复暂存内容并删除该条记录
git stash pop

# 恢复暂存内容但保留记录
git stash apply

2. 修改历史

1
2
3
4
5
# 修改最后一次提交
git commit --amend -m "New commit message"

# 重写历史记录(慎用)
git rebase -i <commit_hash>

3. 回滚

1
2
3
4
5
# 恢复到指定版本(保留历史)
git revert <commit_hash>

# 硬回滚到指定版本(丢弃修改)
git reset --hard <commit_hash>

八、其他有用的命令

1
2
3
4
5
6
7
8
# 查看文件的提交历史
git blame <file>

# 显示某个文件在各版本中的变化
git log -p <file>

# 显示简要的仓库状态
git shortlog

总结

基本上通过这些命令,可以逐步掌握 Git 的基本操作及其进阶功能,从而高效管理代码版本。


一文讲清 Git 基本常用命令
https://dreamshao.github.io/2024/12/12/git/
作者
Yun Shao
发布于
2024年12月12日
许可协议