Git 从入门到精通
前言
Git 作为当今最流行的分布式版本控制系统,已成为每一位开发者必备的技能。无论你是刚入门的新手,还是希望系统梳理知识的中级开发者,本文都将带你全面掌握 Git 的核心命令与最佳实践。
Git 的设计哲学简单而强大:快速、分布式、支持非线性开发。理解这一点,将帮助你更好地运用它的各项功能。
一、环境配置:搭建你的工作空间
在开始使用 Git 之前,首先需要完成基础配置。这些信息将伴随你的每一次代码提交。
1.1 基础身份配置
# 配置全局用户名和邮箱(必须) git config --global user.name "你的名字" git config --global user.email "[email protected]" # 查看当前配置 git config --list # 针对特定仓库配置(去掉 --global 即可) git config user.name "项目特定名字"最佳实践: 使用与代码托管平台(GitHub/GitLab)一致的邮箱,这样提交记录才能正确关联到你的账号。
1.2 提升效率的别名配置
# 为常用命令设置快捷方式 git config --global alias.st status git config --global alias.co checkout git config --global alias.br branch git config --global alias.ci commit git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit" # 现在你可以使用 git st 代替 git status,git lg 查看漂亮的日志二、仓库的生命周期管理
2.1 创建与克隆
# 方式一:在现有目录初始化 mkdir my-project cd my-project git init # 方式二:克隆远程仓库(更常见) git clone https://github.com/username/repository.git # 克隆时指定本地文件夹名称 git clone https://github.com/username/repository.git my-folder # 克隆特定分支 git clone -b develop https://github.com/username/repository.git技术细节:git init 会创建一个 .git 隐藏目录,这就是 Git 的对象数据库,存储着项目的完整历史记录。
2.2 状态检查:你的指南针
git statusgit status 是你在 Git 世界中的指南针,它会告诉你:
- 当前所在分支
- 工作区有哪些修改未暂存
- 暂存区有哪些修改待提交
- 哪些文件未被 Git 跟踪
输出解读示例:
On branch main Your branch is up to date with 'origin/main'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: README.md Untracked files: (use "git add <file>..." to include in what will be committed) new-feature.py三、核心工作流程:从编辑到提交
Git 的核心在于理解三个区域的协作关系:
┌─────────────────┐ git add ┌─────────────────┐ git commit ┌───────────────