Git基础命令速查表
1. 仓库初始化与配置
初始化仓库
bash
复制代码
# 初始化新的Git仓库
git init
# 克隆远程仓库
git clone <repository-url>
git clone https://gitee.com/username/repository.git
配置用户信息
bash
复制代码
# 设置全局用户名和邮箱
git config --global user.name "你的用户名"
git config --global user.email "你的邮箱@example.com"
# 查看配置信息
git config --list
git config user.name
git config user.email
2. 基本操作
查看状态
bash
复制代码
# 查看工作区状态
git status
# 查看文件变更
git diff
git diff --staged # 查看暂存区变更
添加文件
bash
复制代码
# 添加指定文件到暂存区
git add <filename>
git add file1.txt file2.txt
# 添加所有文件到暂存区
git add .
# 添加所有修改的文件
git add -u
提交更改
bash
复制代码
# 提交暂存区的更改
git commit -m "提交信息"
# 添加并提交(跳过暂存区)
git commit -am "提交信息"
查看历史
bash
复制代码
# 查看提交历史
git log
git log --oneline # 简洁模式
git log --graph # 图形化显示
git log -p # 显示详细变更
3. 分支操作
分支管理
bash
复制代码
# 查看分支
git branch
git branch -a # 查看所有分支(包括远程)
# 创建分支
git branch <branch-name>
git branch feature/new-feature
# 切换分支
git checkout <branch-name>
git checkout -b <branch-name> # 创建并切换
# 删除分支
git branch -d <branch-name> # 安全删除
git branch -D <branch-name> # 强制删除
合并分支
bash
复制代码
# 合并分支到当前分支
git merge <branch-name>
# 解决冲突后继续合并
git add .
git commit -m "解决合并冲突"
4. 远程仓库操作
远程仓库管理
bash
复制代码
# 查看远程仓库
git remote -v
# 添加远程仓库
git remote add origin <repository-url>
# 推送代码
git push origin <branch-name>
git push -u origin main # 设置上游分支
# 拉取代码
git pull origin <branch-name>
git fetch origin # 只获取不合并
标签管理
bash
复制代码
# 创建标签
git tag <tag-name>
git tag -a v1.0.0 -m "版本1.0.0"
# 推送标签
git push origin <tag-name>
git push origin --tags
5. 撤销操作
撤销工作区更改
bash
复制代码
# 撤销工作区的修改
git checkout -- <filename>
git restore <filename>
# 撤销所有工作区修改
git checkout -- .
git restore .
撤销暂存区
bash
复制代码
# 撤销暂存区的文件
git reset HEAD <filename>
git restore --staged <filename>
撤销提交
bash
复制代码
# 撤销最后一次提交(保留更改)
git reset --soft HEAD^
# 撤销最后一次提交(丢弃更改)
git reset --hard HEAD^
# 修改最后一次提交信息
git commit --amend
6. 常用技巧
暂存工作
bash
复制代码
# 暂存当前工作
git stash
git stash save "工作描述"
# 查看暂存列表
git stash list
# 恢复暂存的工作
git stash pop
git stash apply stash@{0}
查看信息
bash
复制代码
# 查看文件历史
git blame <filename>
# 查看分支图
git log --graph --oneline --all
# 查看远程分支
git branch -r
7. 常见场景
首次使用Git
bash
复制代码
# 1. 配置用户信息
git config --global user.name "你的名字"
git config --global user.email "你的邮箱"
# 2. 生成SSH密钥
ssh-keygen -t rsa -C "你的邮箱"
# 3. 添加SSH密钥到Gitee
# 复制 ~/.ssh/id_rsa.pub 内容到Gitee设置中
日常开发流程
bash
复制代码
# 1. 拉取最新代码
git pull origin main
# 2. 创建功能分支
git checkout -b feature/new-feature
# 3. 开发并提交
git add .
git commit -m "添加新功能"
# 4. 推送分支
git push origin feature/new-feature
# 5. 在Gitee上创建Pull Request
解决冲突
bash
复制代码
# 1. 拉取最新代码
git pull origin main
# 2. 如果有冲突,手动编辑冲突文件
# 3. 解决冲突后
git add .
git commit -m "解决冲突"
git push origin <branch-name>