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 "[email protected]"

添加文件到仓库

将文件添加到 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>:查看指定提交的详细信息。

参考资料

相关推荐
wumu_Love2 小时前
git 报错:错误:RPC 失败。curl 28 Failed to connect to github.com port 443 after 75000
git·rpc·github
powerfulzyh3 小时前
Git 时光机:修改Commit信息
git
极小狐5 小时前
如何使用极狐GitLab 软件包仓库功能托管 terraform?
linux·运维·git·ssh·gitlab·terraform
等等,要下雨1 天前
git常用命令
git
一直在学习的小白~2 天前
Sourcetree安装使用的详细教程
git
陈苏同学2 天前
从 Git 到 GitHub - 使用 Git 进行版本控制 - Git 常用命令
git·github
影子24012 天前
git项目迁移,包括所有的提交记录和分支 gitlab迁移到gitblit
git·gitlab·git迁移
laimaxgg2 天前
Git撤销修改
git
象骑士Hack2 天前
Xterminal(或 X Terminal)通常指一类现代化的终端工具 工具介绍
git
新时代牛马2 天前
git处理浅克隆
git