1.0 入门
2.1基础概念
版本控制系统:Git 是一个分布式版本控制系统,用于跟踪文件变化并协作开发代码。
核心概念:
- 仓库(Repository):项目文件夹,包含所有文件和历史记录
- 提交(Commit):保存项目状态的快照
- 分支(Branch):独立开发线,默认有 main/master 分支
- 远程(Remote):托管在服务器上的仓库副本(如 GitHub)
2.2安装与配置
3.1 安装 Git
- Windows:下载 Git for Windows
- macOS:
brew install git(需先安装 Homebrew) - Linux:
sudo apt install git(Ubuntu/Debian)
3.2基础配置
创建配置
# 设置用户名和邮箱(全局配置) git config --global user.name "你的名字" git config --global user.email "你的邮箱"
查看配置
git config --list
添加与提交
```shell
# 添加文件到暂存区
git add 文件名 # 添加单个文件
git add . # 添加所有修改
# 提交到本地仓库
git commit -m "提交说明"
查看状态与历史
git status # 查看当前状态
git log # 查看提交历史
git diff # 查看文件修改内容
3.3分支管理
# 创建分支
git branch 新分支名
# 切换分支
git checkout 分支名
# 或(Git 2.23+)
git switch 分支名
# 创建并切换分支
git checkout -b 新分支名
# 合并分支
git checkout main
git merge 分支名
# 删除分支
git branch -d 分支名
3.4远程仓库操作
连接远程仓库
# 添加远程仓库
git remote add origin https://github.com/用户名/仓库名.git
# 查看远程仓库
git remote -v
推送与拉取
# 推送本地分支到远程
git push -u origin 分支名 # 首次推送用 -u
git push # 后续推送
# 拉取远程更新
git pull origin 分支名
克隆与协作
# 克隆仓库
git clone https://github.com/用户名/仓库名.git
# 获取最新代码(不自动合并)
git fetch origin
# 创建拉取请求(Pull Request)
# 在 GitHub 界面上操作
3.5实用技巧
撤销操作
# 撤销暂存的文件
git reset 文件名
# 修改最后一次提交
git commit --amend
# 恢复文件到上次提交状态
git checkout -- 文件名
忽略文件
创建 .gitignore文件,列出要忽略的文件/文件夹:
# 示例
node_modules/
*.log
.DS_Store
1.1进阶
2.1将开源的仓库克隆到自己的仓库管理
将克隆的开源工程推送到自己的GitHub仓库,需要解除与原仓库的关联,添加新远程地址:
# 1. 进入克隆的仓库目录
cd project-name
# 2. 移除原仓库的远程关联
git remote remove origin
# 3. 在GitHub创建新空仓库(不要初始化README)
# 4. 添加你的GitHub仓库为新的远程源
git remote add origin https://github.com/你的用户名/新仓库名.git
# 5. 推送所有分支和标签
git push -u origin --all # 推送所有分支
git push origin --tags # 推送所有标签
github创建新空仓库方法github仓库建立及配置教程新手教程_github创建仓库-CSDN博客
2.2将本地工程上传到github仓库
3.1步骤
1、准备本地仓库
# 进入项目目录
cd your-project-folder
# 初始化 Git 仓库
git init
# 添加所有文件到暂存区
git add .
# 提交初始版本
git commit -m "Initial commit"
2、创建github仓库
3、连接远程仓库并推送
# 添加 GitHub 仓库作为远程源(替换URL)
git remote add origin https://github.com/你的用户名/仓库名.git
# 验证远程连接
git remote -v
# 推送代码到 GitHub(首次推送使用 -u 参数)
git push -u origin main
# 如果遇到错误,可能是分支名不同:
git branch -M main # 将主分支重命名为 main(GitHub 默认)
git push -u origin main
注:首次推送后,后续更新只需:
git add .
git commit -m "更新描述"
git push
3.2常见问题解决
文件太大被拒绝
# 添加 .gitignore 文件忽略大文件
echo "large-file.zip" >> .gitignore
git add .gitignore
git commit -m "Add .gitignore"
git push
3.3最佳实践建议
1、定期提交:小步提交,保持提交信息清晰
git add changed-file.js
git commit -m "修复登录页面样式问题"
2、使用分支开发:
git checkout -b feature/new-login
# 开发完成后...
git push origin feature/new-login
3、保持同步:
# 每次推送前先拉取最新代码
git pull origin main
Comments NOTHING