Git 使用大全

Git 是一个分布式版本控制系统,常用于软件开发中的代码管理。下面我将从基础到高级,全面介绍 Git 的使用方法。

1. 安装与配置

首先需要安装 Git,然后进行全局配置,设置用户名和邮箱:
# 安装Git(以Ubuntu为例)
sudo apt-get install git

# 配置用户名和邮箱
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

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

2. 基础操作

创建仓库

# 在现有目录中初始化仓库
git init

# 克隆远程仓库
git clone https://github.com/username/repo.git

提交更改

# 添加文件到暂存区
git add filename.txt  # 添加单个文件
git add .           # 添加所有文件

# 提交到本地仓库
git commit -m "提交说明"

# 查看状态
git status

# 查看提交历史
git log
git log --oneline  # 简洁格式

3. 分支管理

# 查看分支
git branch

# 创建分支
git branch new-branch

# 切换分支
git checkout new-branch

# 创建并切换分支
git checkout -b new-branch

# 合并分支
git checkout main  # 切换到主分支
git merge new-branch  # 合并新分支

# 删除分支
git branch -d new-branch  # 已合并的分支
git branch -D new-branch  # 未合并的分支

4. 远程仓库操作

# 添加远程仓库
git remote add origin https://github.com/username/repo.git

# 查看远程仓库
git remote -v

# 推送本地分支到远程
git push -u origin main  # 第一次推送
git push  # 后续推送

# 拉取远程更新
git pull origin main

# 拉取远程分支但不自动合并
git fetch origin

5. 撤销与回滚

# 撤销工作区修改
git checkout -- filename.txt

# 撤销暂存区修改
git reset HEAD filename.txt

# 回滚到指定提交
git reset --hard commit-hash

# 创建新提交来回滚
git revert commit-hash

6. 标签管理

# 创建轻量标签
git tag v1.0

# 创建带注释标签
git tag -a v1.0 -m "版本1.0发布"

# 查看标签
git tag

# 推送标签到远程
git push origin v1.0
git push origin --tags  # 推送所有标签

7. 高级技巧

储藏(Stash)

# 储藏当前修改
git stash

# 查看储藏列表
git stash list

# 应用最近的储藏
git stash apply

# 应用并删除储藏
git stash pop

# 删除储藏
git stash drop stash@{0}

变基(Rebase)

# 在main分支上拉取最新更新
git checkout main
git pull

# 切换到feature分支进行变基
git checkout feature
git rebase main

子模块(Submodule)

# 添加子模块
git submodule add https://github.com/username/submodule.git

# 克隆包含子模块的项目
git clone --recursive https://github.com/username/repo.git

# 更新子模块
git submodule update --init --recursive

8. 配置别名

# 设置常用命令的别名
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status

# 使用别名
git co main  # 相当于 git checkout main

9. 忽略文件

创建 .gitignore 文件,列出要忽略的文件和目录:
# 忽略所有 .log 文件
*.log

# 忽略 node_modules 目录
node_modules/

# 忽略特定文件
secrets.txt

10. 解决冲突

当合并分支或拉取更新时可能会发生冲突,需要手动解决:
# 拉取更新导致冲突
git pull

# 查看冲突文件
git status

# 手动编辑冲突文件,解决冲突后
git add conflicted-file.txt
git commit
以上就是 Git 的主要使用方法,掌握这些命令可以满足日常开发中的大部分需求。
阅读剩余
THE END