-
全局配置用户名和邮箱
bash
git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
-
查看配置信息
bash
git config --list # 查看所有配置 git config user.name # 查看特定配置
仓库操作
-
初始化仓库
bash
git init # 在当前目录创建新仓库
-
克隆远程仓库
bash
git clone https://github.com/user/repo.git # 克隆远程仓库到本地 git clone -b branch_name https://github.com/user/repo.git # 克隆指定分支
文件状态与提交
-
查看文件状态
bash
git status # 查看文件修改状态
-
添加文件到暂存区
bash
git add file.txt # 添加单个文件 git add . # 添加所有修改文件(当前目录) git add -u # 添加已跟踪文件的修改(不包括新增文件)
-
提交到本地仓库
bash
git commit -m "Commit message" # 提交暂存区的文件 git commit -am "Commit message" # 直接提交已跟踪文件的修改(跳过add)
-
撤销修改
bash
git restore file.txt # 撤销工作区的修改(回到上一次add或commit状态) git restore --staged file.txt # 取消暂存区的文件(从add回到未add状态)
分支管理
-
查看分支
bash
git branch # 查看本地分支 git branch -r # 查看远程分支 git branch -a # 查看所有分支(本地+远程)
-
创建分支
bash
git branch new_branch # 创建新分支 git checkout -b new_branch # 创建并切换到新分支
-
切换分支
bash
git checkout branch_name # 切换到已存在的分支
-
合并分支
bash
git merge branch_name # 将指定分支合并到当前分支
-
删除分支
bash
git branch -d branch_name # 删除已合并的分支 git branch -D branch_name # 强制删除未合并的分支
远程仓库操作
-
关联远程仓库
bash
git remote add origin https://github.com/user/repo.git # 添加远程仓库
-
推送代码到远程仓库
bash
git push -u origin main # 首次推送本地main分支到远程 git push origin branch_name # 推送指定分支到远程
-
拉取远程代码
bash
git pull origin main # 拉取远程main分支并合并到本地
-
查看远程仓库信息
bash
git remote -v # 查看远程仓库地址
历史记录与回滚
-
查看提交历史
bash
git log # 查看提交历史 git log --oneline # 简洁模式查看历史
-
回滚到指定提交
bash
git reset --hard commit_hash # 回滚到指定提交(丢弃后续提交) git revert commit_hash # 创建一个新提交来撤销指定提交(保留历史)
标签管理
-
创建标签
bash
git tag v1.0 # 创建轻量标签 git tag -a v1.0 -m "Version 1.0" # 创建带注释的标签
-
推送标签到远程
bash
git push origin v1.0 # 推送单个标签 git push origin --tags # 推送所有标签
其他常用命令
-
暂存当前修改
bash
git stash # 暂存当前未提交的修改 git stash pop # 恢复最近一次stash的修改
-
查看文件差异
bash
git diff # 查看工作区与暂存区的差异 git diff --staged # 查看暂存区与最后一次提交的差异
常见场景示例
-
创建新分支并提交代码
bash
git checkout -b feature/new-feature # 创建并切换到新特性分支 # 编写代码... git add . git commit -m "Add new feature" git push origin feature/new-feature # 推送到远程
-
解决合并冲突
bash
git merge branch_name # 合并时出现冲突 # 手动编辑冲突文件,删除冲突标记 git add conflict_file.txt git commit # 完成合并