Git - 环境设置
Git - 环境设置
Section titled “Git - 环境设置”在开始使用 Git 之前,你需要在系统上安装它并进行一些初始配置。这个设置过程通常只需要一次。
在基于 Debian 的发行版(如 Ubuntu)上:
$ sudo apt update$ sudo apt install git在基于 RPM 的发行版(如 Fedora, CentOS/RHEL)上:
# For Fedora$ sudo dnf install git
# For CentOS/RHEL$ sudo yum install git最简单的方法是安装 Xcode 命令行工具(Xcode Command Line Tools)。如果你第一次在终端 (terminal) 中尝试运行 git 命令,系统会提示你安装它们。此外,你也可以使用 Homebrew 安装 Git:
$ brew install gitWindows
Section titled “Windows”从 https://git-scm.com/download/win 下载并安装 Git for Windows。它包含了 Git BASH (一个命令行工具) 和一个 GUI 客户端。
安装完成后,打开一个终端(或 Windows 上的 Git BASH),输入以下命令来验证安装:
$ git --versiongit version 2.xx.xGit 使用一个名为 git config 的工具来设置配置变量。这些设置可以存储在三个级别:
--system: 系统级别 (/etc/gitconfig)。影响所有用户和仓库 (repository)。需要 root/管理员 权限。--global: 用户级别 (~/.gitconfig或~/.config/git/config)。影响当前用户的所有仓库。这是设置个人偏好最常用的级别。--local: 仓库级别 (.git/config在当前仓库中)。仅影响当前仓库。如果未指定选项,这是默认级别。
这些信息将嵌入到你所做的每一个 commit (提交) 中。全局设置它们:
$ git config --global user.name "Your Name"$ git config --global user.email "your.email@example.com"默认分支名称
Section titled “默认分支名称”当前的惯例是使用 main 作为新仓库的默认分支名称。配置 Git 使用 main:
$ git config --global init.defaultBranch mainGit 使用你系统的默认编辑器来编写 commit (提交) 消息。你可以指定一个不同的编辑器(例如 Vim, Nano, VS Code):
# Example for Vim$ git config --global core.editor vim
# Example for VS Code (ensure 'code' is in your PATH)# $ git config --global core.editor "code --wait"正如“不同平台”章节所讨论的,配置行结束符处理方式(以下示例适用于跨平台项目,假设会针对每个项目使用 .gitattributes 进行细粒度控制):
# For Windows users$ git config --global core.autocrlf true
# For macOS/Linux users$ git config --global core.autocrlf inputPull (拉取) 行为 (Rebase 重写历史 vs. Merge 合并)
Section titled “Pull (拉取) 行为 (Rebase 重写历史 vs. Merge 合并)”当你执行 git pull 时,Git 会获取变更然后合并 (merge) 它们。你可以配置 Git 使用 rebase (重写历史) 代替 merge:
# To make `git pull` use rebase by default for new branches$ git config --global pull.rebase true
# Alternatively, to keep the default merge behavior (common for beginners):# $ git config --global pull.rebase false使用 pull.rebase = true 可以帮助维护更干净、更线性的项目历史。但是,在全局启用此选项之前,请确保你理解 rebase 的概念。
在 Git 的输出中启用颜色高亮以提高可读性:
$ git config --global color.ui auto默认 Push (推送) 行为
Section titled “默认 Push (推送) 行为”现代 Git 默认使用 simple 推送行为,这更安全。它会将当前分支推送到其同名的上游对应分支。你可以确保此设置已配置:
$ git config --global push.default simple列出 Git 设置
Section titled “列出 Git 设置”要查看所有全局 Git 设置:
$ git config --global --list这将输出你配置的设置,例如:
user.name=Your Nameuser.email=your.email@example.cominit.defaultbranch=maincore.editor=vimcore.autocrlf=true # (or input)pull.rebase=true # (or false)color.ui=autopush.default=simple你也可以进入特定仓库目录,运行 git config --local --list 来查看该仓库的设置。