Git使用步骤

Git 是一个分布式版本控制系统,广泛用于软件开发和其他需要跟踪文件变更的项目。以下是 Git 的基本使用方法和一些常用命令的详细说明。

安装 Git

在大多数操作系统上,你可以通过包管理器安装 Git:

  • Windows :
  • MacOS :
    • 使用 Homebrew 安装:brew install git
  • Linux :
    • 使用包管理器安装,例如在 Ubuntu 上:sudo apt-get install git

初始化 Git 仓库

在项目目录中初始化一个新的 Git 仓库:

复制代码
git init

配置 Git

首次使用 Git 时,需要配置用户信息:

复制代码
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

添加文件到仓库

将文件添加到 Git 的暂存区:

复制代码
git add <file>

添加所有文件:

复制代码
git add .

提交更改

将暂存区的文件提交到仓库:

复制代码
git commit -m "Commit message"

查看状态

查看当前工作目录的状态:

复制代码
git status

查看提交历史

查看提交历史记录:

复制代码
git log

查看简洁的提交历史:

复制代码
git log --oneline

分支管理

创建分支

创建并切换到新分支:

复制代码
git branch <branch-name>
git checkout <branch-name>

或者使用简化的命令:

复制代码
git checkout -b <branch-name>
切换分支

切换到指定分支:

复制代码
git checkout <branch-name>
查看分支

查看当前所有分支:

复制代码
git branch
合并分支

将一个分支的更改合并到当前分支:

复制代码
git merge <branch-name>

拉取和推送

克隆仓库

克隆一个远程仓库到本地:

cpp 复制代码
git clone <repository-url>
添加远程仓库

添加一个远程仓库:

复制代码
git remote add <remote-name> <repository-url>
拉取更新

从远程仓库拉取最新的更改:

复制代码
git pull <remote-name> <branch-name>
推送更改

将本地更改推送到远程仓库:

复制代码
git push <remote-name> <branch-name>

撤销更改

撤销工作区的更改

撤销工作区中的更改,恢复到最近一次提交的状态:

复制代码
git checkout -- <file>
撤销暂存区的更改

将已经添加到暂存区的文件移出暂存区:

复制代码
git reset <file>
撤销最后一次提交

撤销最后一次提交,但保留所有更改在工作区:

复制代码
git reset --soft HEAD~1

撤销最后一次提交,并丢弃所有更改:

复制代码
git reset --hard HEAD~1

标签管理

创建标签

创建一个标签:

复制代码
git tag <tag-name>

创建一个带有注释的标签:

复制代码
git tag -a <tag-name> -m "Tag message"
查看标签

查看所有标签:

复制代码
git tag
推送标签

将标签推送到远程仓库:

复制代码
git push <remote-name> <tag-name>

推送所有标签:

复制代码
git push <remote-name> --tags

忽略文件

创建一个 .gitignore 文件,列出不需要跟踪的文件或目录:

复制代码
# .gitignore
*.log
*.swp

恢复文件

从仓库中恢复已删除的文件:

复制代码
git checkout <commit-hash> -- <file>

高级用法

交互式添加

使用交互式模式将文件添加到暂存区:

复制代码
git add -i
交互式提交

使用交互式模式提交更改:

复制代码
git commit --interactive
质量检查

使用 git diff 查看工作区和暂存区的差异:

复制代码
git diff

查看暂存区和最后一次提交的差异:

复制代码
git diff --cached

常用快捷键

  • git log -p:查看每次提交的详细更改。

  • git blame <file>:查看文件的每一行是谁最后一次修改的。

  • git show <commit-hash>:查看指定提交的详细信息。

参考资料

相关推荐
Franklin9 小时前
VS 版本更新git安全保护问题的解决
git
我是一只代码狗13 小时前
idea中合并git分支
git
我是一只代码狗13 小时前
idea中使用git
git·gitee·github
恋喵大鲤鱼13 小时前
git restore
git·git restore
李少兄14 小时前
Git Commit Message写错后如何修改?已Push的提交如何安全修复?
git·安全
Fireworkitte14 小时前
git stash
git
pe7er1 天前
git submodule简易指南
git
xiaocainiao8811 天前
Python 实战:构建 Git 自动化助手
git·python·自动化
Casia_Dominic2 天前
【三维重建工具】NeRFStudio、3D GaussianSplatting、Colmap安装与使用指南
git·3d·github·点云