git使用详解和示例_git仓库使用举例
什么是 Git?
Git 是一个 分布式版本控制系统(DVCS),用于跟踪文件的变化,协调多人协作开发。由 Linus Torvalds 开发,用于管理 Linux 内核代码。
Git 的核心概念
git add
的作用)。git commit
存入)。Git 文件的四种状态
Untracked → Staged → Committed ↑ ↓ Modified (Reset)
- Untracked:新文件,未被 Git 管理。
- Modified:已修改但未添加到暂存区。
- Staged:使用
git add
添加后进入。 - Committed:用
git commit
记录后存入仓库历史。
Git 安装与配置
安装
- Windows: Git for Windows
- macOS:
brew install git
- Linux:
sudo apt install git
全局配置
git config --global user.name \"Your Name\"git config --global user.email \"you@example.com\"git config --global core.editor \"code\" # 设置默认编辑器
常用 Git 命令(分类整理)
1. 仓库管理
git init # 初始化一个仓库git clone <url> # 克隆远程仓库
2. 文件操作
git status # 查看当前状态git add <file|.> # 添加到暂存区git commit -m \"描述\" # 提交更改git rm <file> # 删除文件并加入提交git mv <old> <new> # 重命名文件
3. 查看历史
git log # 提交历史git log --oneline # 简洁视图git show <commit> # 查看某次提交的详细内容git diff # 当前工作区 vs 暂存区git diff --cached # 暂存区 vs 上次提交
4. 分支管理
git branch # 查看分支git branch <name> # 创建分支git checkout <name> # 切换分支git checkout -b <name> # 创建并切换分支git merge <branch> # 合并分支git branch -d <name> # 删除分支
5. 远程操作
git remote add origin <url> # 添加远程仓库git fetch # 获取远程更新git pull origin <branch> # 拉取远程分支并合并git push origin <branch> # 推送本地分支git push -u origin <branch> # 设置默认推送分支
6. 回退与重置
git checkout -- <file> # 撤销对某文件的修改git reset HEAD <file> # 取消暂存某文件git reset --soft HEAD~1 # 回退上一次提交,保留修改git reset --hard HEAD~1 # 强制回退,丢弃修改
7. 标签管理
git tag v1.0git tag -a v1.0 -m \"发布版本\"git show v1.0git push origin v1.0
Git 工作流示例(推荐流程)
示例:多人协作开发流程
- 克隆项目:
git clone https://github.com/user/project.gitcd project
- 创建分支开发:
git checkout -b feature/login
- 编辑代码,提交:
git add .git commit -m \"feat: 完成登录功能\"
- 合并分支:
git checkout maingit pullgit merge feature/logingit push
- 清理:
git branch -d feature/login
.gitignore
文件
.gitignore
用于告诉 Git 忽略哪些文件:
# 忽略编译文件*.o*.exebuild/# 忽略日志*.log# 忽略 IDE 文件.vscode/.idea/
高级命令与技巧
git stash
/ git stash pop
git blame filename
gitk
/ git log --graph
git checkout
git reset --soft HEAD~1
git config --global alias.co checkout
等Git 图形工具推荐
Git 练习网站推荐
- https://learngitbranching.js.org
- https://git-school.github.io/visualizing-git
小结
git init
, git clone
git add
, git commit
git status
, git log
git branch
, git checkout
, git merge
git push
, git pull
, git remote
git reset
, git checkout
, git stash